From b8995da5eab8b67490ccbd85e24b9fbaf4f2f54e Mon Sep 17 00:00:00 2001 From: Developer 02 Date: Mon, 19 May 2025 15:21:11 +0200 Subject: [PATCH] Refactor global exception handling middleware Updated `GlobalExceptionHandlerMiddleware.cs` to include necessary using directives for logging and options handling. Removed the `HandleExceptionAsync` method and replaced it with a more extensible approach using a dictionary of handlers for different exception types. Added logging for unhandled exceptions to ensure proper error tracking. --- .../GlobalExceptionHandlerMiddleware.cs | 50 +++---------------- 1 file changed, 7 insertions(+), 43 deletions(-) diff --git a/DigitalData.Core.Exceptions.Middleware/GlobalExceptionHandlerMiddleware.cs b/DigitalData.Core.Exceptions.Middleware/GlobalExceptionHandlerMiddleware.cs index d52e148..4f73279 100644 --- a/DigitalData.Core.Exceptions.Middleware/GlobalExceptionHandlerMiddleware.cs +++ b/DigitalData.Core.Exceptions.Middleware/GlobalExceptionHandlerMiddleware.cs @@ -1,10 +1,8 @@ -namespace DigitalData.Core.Exceptions.Middleware; - -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using System.Net; -using System.Text.Json; + +namespace DigitalData.Core.Exceptions.Middleware; /// /// Middleware for handling exceptions globally in the application. @@ -44,45 +42,11 @@ public class GlobalExceptionHandlerMiddleware } catch (Exception ex) { - await HandleExceptionAsync(context, ex, _logger); - } - } - - /// - /// Handles exceptions by logging them and writing an appropriate JSON response. - /// - /// The HTTP context of the current request. - /// The exception that occurred. - /// The logger instance for logging the exception. - /// A task that represents the asynchronous operation. - private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger? logger = null) - { - context.Response.ContentType = "application/json"; - - string message; - - switch (exception) - { - case BadRequestException badRequestEx: - context.Response.StatusCode = (int)HttpStatusCode.BadRequest; - message = badRequestEx.Message; - break; - - case NotFoundException notFoundEx: - context.Response.StatusCode = (int)HttpStatusCode.NotFound; - message = notFoundEx.Message; - break; + if(ex.GetType() == typeof(Exception)) + _options?.DefaultHandler?.HandleExceptionAsync.Invoke(context, ex, _logger); - default: - logger?.LogError(exception, "Unhandled exception occurred."); - context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - message = "An unexpected error occurred."; - break; + if (_options?.Handlers.TryGetValue(ex.GetType(), out var handler) ?? false) + handler?.HandleExceptionAsync.Invoke(context, ex, _logger); } - - await context.Response.WriteAsync(JsonSerializer.Serialize(new - { - message - })); } }