2024-05-28 07:16:15 +03:00
|
|
|
|
using FluentValidation;
|
|
|
|
|
using Microsoft.AspNetCore.Http;
|
2024-10-27 03:02:25 +03:00
|
|
|
|
using Microsoft.Extensions.Logging;
|
2024-05-28 07:16:15 +03:00
|
|
|
|
using Mirea.Api.DataAccess.Application.Common.Exceptions;
|
|
|
|
|
using Mirea.Api.Dto.Responses;
|
|
|
|
|
using Mirea.Api.Endpoint.Common.Exceptions;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
2024-10-07 02:25:36 +03:00
|
|
|
|
namespace Mirea.Api.Endpoint.Configuration.Core.Middleware;
|
2024-05-28 07:16:15 +03:00
|
|
|
|
|
2024-10-27 03:02:25 +03:00
|
|
|
|
public class CustomExceptionHandlerMiddleware(RequestDelegate next, ILogger<CustomExceptionHandlerMiddleware> logger)
|
2024-05-28 07:16:15 +03:00
|
|
|
|
{
|
2024-08-12 21:36:07 +03:00
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
2024-05-28 07:16:15 +03:00
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await next(context);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception exception)
|
|
|
|
|
{
|
|
|
|
|
await HandleExceptionAsync(context, exception);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-27 03:02:25 +03:00
|
|
|
|
private Task HandleExceptionAsync(HttpContext context, Exception exception)
|
2024-05-28 07:16:15 +03:00
|
|
|
|
{
|
|
|
|
|
var code = StatusCodes.Status500InternalServerError;
|
|
|
|
|
var result = string.Empty;
|
|
|
|
|
switch (exception)
|
|
|
|
|
{
|
|
|
|
|
case ValidationException validationException:
|
|
|
|
|
code = StatusCodes.Status400BadRequest;
|
|
|
|
|
result = JsonSerializer.Serialize(new ErrorResponse()
|
|
|
|
|
{
|
|
|
|
|
Error = validationException.Message,
|
|
|
|
|
Code = code
|
|
|
|
|
});
|
|
|
|
|
break;
|
|
|
|
|
case NotFoundException:
|
|
|
|
|
code = StatusCodes.Status404NotFound;
|
|
|
|
|
break;
|
|
|
|
|
case ControllerArgumentException:
|
|
|
|
|
code = StatusCodes.Status400BadRequest;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
context.Response.ContentType = "application/json";
|
|
|
|
|
context.Response.StatusCode = code;
|
|
|
|
|
|
2024-10-27 03:02:25 +03:00
|
|
|
|
if (!string.IsNullOrEmpty(result))
|
|
|
|
|
return context.Response.WriteAsync(result);
|
|
|
|
|
|
|
|
|
|
string error;
|
|
|
|
|
if (code == StatusCodes.Status500InternalServerError)
|
|
|
|
|
{
|
|
|
|
|
error = "Internal Server Error";
|
|
|
|
|
logger.LogError("Internal server error: {Message}\nStackTrace:\n{StackTrace}", exception.Message, exception.StackTrace);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
error = exception.Message;
|
|
|
|
|
|
|
|
|
|
result = JsonSerializer.Serialize(new ErrorResponse()
|
|
|
|
|
{
|
|
|
|
|
Error = error,
|
|
|
|
|
Code = code
|
|
|
|
|
});
|
2024-05-28 07:16:15 +03:00
|
|
|
|
|
|
|
|
|
return context.Response.WriteAsync(result);
|
|
|
|
|
}
|
|
|
|
|
}
|