using FluentValidation; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Mirea.Api.DataAccess.Application.Common.Exceptions; using Mirea.Api.Dto.Responses; using Mirea.Api.Endpoint.Common.Exceptions; using System; using System.Security; using System.Text.Json; using System.Threading.Tasks; namespace Mirea.Api.Endpoint.Configuration.Core.Middleware; public class CustomExceptionHandlerMiddleware(RequestDelegate next, ILogger logger) { public async Task InvokeAsync(HttpContext context) { try { await next(context); } catch (Exception exception) { await HandleExceptionAsync(context, exception); } } private Task HandleExceptionAsync(HttpContext context, Exception exception) { 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; case SecurityException: code = StatusCodes.Status401Unauthorized; break; } context.Response.ContentType = "application/json"; context.Response.StatusCode = code; if (!string.IsNullOrEmpty(result)) return context.Response.WriteAsync(result); string error; if (code == StatusCodes.Status500InternalServerError) { error = "Internal Server Error"; logger.LogError(exception, "Internal server error when processing the request"); } else error = exception.Message; result = JsonSerializer.Serialize(new ErrorResponse() { Error = error, Code = code }); return context.Response.WriteAsync(result); } }