From a4afbc43b224923785a7524c7ecd63d004afb609 Mon Sep 17 00:00:00 2001 From: Hayotbahrom Nurdinov Date: Mon, 5 Feb 2024 15:53:57 +0500 Subject: [PATCH] CustomMiddleware added --- EventBor.Backend.API/Helpers/Response.cs | 8 +++++ .../Middlewares/ExceptionHandlerMiddkeware.cs | 36 +++++++++++++++++++ .../Exceptions/EventBorException.cs | 10 ++++++ 3 files changed, 54 insertions(+) create mode 100644 EventBor.Backend.API/Helpers/Response.cs create mode 100644 EventBor.Backend.API/Middlewares/ExceptionHandlerMiddkeware.cs create mode 100644 EventBor.Backend.Application/Exceptions/EventBorException.cs diff --git a/EventBor.Backend.API/Helpers/Response.cs b/EventBor.Backend.API/Helpers/Response.cs new file mode 100644 index 0000000..f5fd2b4 --- /dev/null +++ b/EventBor.Backend.API/Helpers/Response.cs @@ -0,0 +1,8 @@ +namespace EventBor.Backend.API.Helpers; + +public class Response +{ + public int StatusCode { get; set; } = 200; + public string Message { get; set; } + public object Data { get; set; } +} diff --git a/EventBor.Backend.API/Middlewares/ExceptionHandlerMiddkeware.cs b/EventBor.Backend.API/Middlewares/ExceptionHandlerMiddkeware.cs new file mode 100644 index 0000000..94c2e25 --- /dev/null +++ b/EventBor.Backend.API/Middlewares/ExceptionHandlerMiddkeware.cs @@ -0,0 +1,36 @@ +using EventBor.Backend.API.Helpers; +using EventBor.Backend.Application.Exceptions; + +namespace EventBor.Backend.API.Middlewares; + +public class ExceptionHandlerMiddkeware +{ + private readonly RequestDelegate _next; + + public async Task Invoke(HttpContext context) + { + try + { + await _next(context); + } + catch (EventBorException ex) + { + context.Response.StatusCode = ex.StatusCode; + await context.Response.WriteAsJsonAsync(new Response + { + StatusCode = ex.StatusCode, + Message = ex.Message + }); + } + catch (Exception ex) + { + context.Response.StatusCode = 500; + await context.Response.WriteAsJsonAsync(new Response + { + StatusCode = 500, + Message = ex.Message + }); + } + } +} + diff --git a/EventBor.Backend.Application/Exceptions/EventBorException.cs b/EventBor.Backend.Application/Exceptions/EventBorException.cs new file mode 100644 index 0000000..26fd50b --- /dev/null +++ b/EventBor.Backend.Application/Exceptions/EventBorException.cs @@ -0,0 +1,10 @@ +namespace EventBor.Backend.Application.Exceptions; + +public class EventBorException : Exception +{ + public int StatusCode { get; set; } + public EventBorException(int code, string message) : base(message) + { + StatusCode = code; + } +}