From 481839159cdb60c7bf8f02f92d27a91878c3a30c Mon Sep 17 00:00:00 2001 From: Polianin Nikita Date: Tue, 28 May 2024 07:16:15 +0300 Subject: [PATCH] feat: add middleware for custom exception --- .../CustomExceptionHandlerMiddleware.cs | 60 +++++++++++++++++++ Endpoint/Program.cs | 1 + 2 files changed, 61 insertions(+) create mode 100644 Endpoint/Middleware/CustomExceptionHandlerMiddleware.cs diff --git a/Endpoint/Middleware/CustomExceptionHandlerMiddleware.cs b/Endpoint/Middleware/CustomExceptionHandlerMiddleware.cs new file mode 100644 index 0000000..62c41e2 --- /dev/null +++ b/Endpoint/Middleware/CustomExceptionHandlerMiddleware.cs @@ -0,0 +1,60 @@ +using FluentValidation; +using Microsoft.AspNetCore.Http; +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; + +namespace Mirea.Api.Endpoint.Middleware; + +public class CustomExceptionHandlerMiddleware(RequestDelegate next) +{ + public async Task Invoke(HttpContext context) + { + try + { + await next(context); + } + catch (Exception exception) + { + await HandleExceptionAsync(context, exception); + } + } + + private static 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; + } + + context.Response.ContentType = "application/json"; + context.Response.StatusCode = code; + + if (string.IsNullOrEmpty(result)) + result = JsonSerializer.Serialize(new ErrorResponse() + { + Error = exception.Message, + Code = code + }); + + return context.Response.WriteAsync(result); + } +} \ No newline at end of file diff --git a/Endpoint/Program.cs b/Endpoint/Program.cs index 0938434..89d98ab 100644 --- a/Endpoint/Program.cs +++ b/Endpoint/Program.cs @@ -138,6 +138,7 @@ public class Program }); } app.UseMiddleware(); + app.UseMiddleware(); app.UseHttpsRedirection();