From 9e181c26310160a68c2e098b7cc13a37bd5fcaee Mon Sep 17 00:00:00 2001 From: Legolas2222 <95238358+Legolas2222@users.noreply.github.com> Date: Thu, 19 Oct 2023 20:44:05 +0200 Subject: [PATCH] Feat: Added Middleware for catching double register error; now returns general error. Still needs work --- .../Middleware/ErrorHandlingMiddleware.cs | 32 +++++++++++++++++++ TodoistClone.Api/Program.cs | 6 +++- 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 TodoistClone.Api/Middleware/ErrorHandlingMiddleware.cs diff --git a/TodoistClone.Api/Middleware/ErrorHandlingMiddleware.cs b/TodoistClone.Api/Middleware/ErrorHandlingMiddleware.cs new file mode 100644 index 000000000000..bead9f3d049b --- /dev/null +++ b/TodoistClone.Api/Middleware/ErrorHandlingMiddleware.cs @@ -0,0 +1,32 @@ +using System.Net; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace TodoistClone.Api.Middleware; + +public class ErrorHandlingMiddlware +{ + private readonly RequestDelegate _next; + + public ErrorHandlingMiddlware(RequestDelegate next) { + _next = 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 = HttpStatusCode.InternalServerError; + var result = JsonSerializer.Serialize(new { error = "An error occured while processing your request." }); + context.Response.ContentType = "application/json"; + context.Response.StatusCode = (int)code; + return context.Response.WriteAsync(result); + } +} + diff --git a/TodoistClone.Api/Program.cs b/TodoistClone.Api/Program.cs index e0063e78a788..b19b444dccc9 100644 --- a/TodoistClone.Api/Program.cs +++ b/TodoistClone.Api/Program.cs @@ -1,3 +1,4 @@ +using TodoistClone.Api.Middleware; using TodoistClone.Application; using TodoistClone.Infrastructure; @@ -22,11 +23,14 @@ } */ var app = builder.Build(); - +{ //app.UseHttpsRedirection(); +app.UseMiddleware(); app.UseAuthorization(); app.MapControllers(); app.Run(); + +}