From 972b258706e80a2b40fd650da572d7943f8c3ab1 Mon Sep 17 00:00:00 2001 From: Developer 02 Date: Fri, 9 May 2025 10:35:04 +0200 Subject: [PATCH] Refactor exception handling in middleware Updated `HandleExceptionAsync` to set response status directly for each exception type and streamlined JSON serialization of error messages. --- .../Middleware/ExceptionHandlingMiddleware.cs | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/EnvelopeGenerator.GeneratorAPI/Middleware/ExceptionHandlingMiddleware.cs b/EnvelopeGenerator.GeneratorAPI/Middleware/ExceptionHandlingMiddleware.cs index 2ac95f3e..f9d700a1 100644 --- a/EnvelopeGenerator.GeneratorAPI/Middleware/ExceptionHandlingMiddleware.cs +++ b/EnvelopeGenerator.GeneratorAPI/Middleware/ExceptionHandlingMiddleware.cs @@ -54,37 +54,31 @@ public class ExceptionHandlingMiddleware private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger logger) { context.Response.ContentType = "application/json"; - var response = context.Response; string message; - int statusCode; switch (exception) { case BadRequestException badRequestEx: - statusCode = (int)HttpStatusCode.BadRequest; + context.Response.StatusCode = (int)HttpStatusCode.BadRequest; message = badRequestEx.Message; break; case NotFoundException notFoundEx: - statusCode = (int)HttpStatusCode.NotFound; + context.Response.StatusCode = (int)HttpStatusCode.NotFound; message = notFoundEx.Message; break; default: logger.LogError(exception, "Unhandled exception occurred."); - statusCode = (int)HttpStatusCode.InternalServerError; + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; message = "An unexpected error occurred."; break; } - response.StatusCode = statusCode; - - var result = JsonSerializer.Serialize(new + await context.Response.WriteAsync(JsonSerializer.Serialize(new { - error = message - }); - - await context.Response.WriteAsync(result); + message + })); } }