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); + if(ex.GetType() == typeof(Exception)) + _options?.DefaultHandler?.HandleExceptionAsync.Invoke(context, ex, _logger); + + if (_options?.Handlers.TryGetValue(ex.GetType(), out var handler) ?? false) + handler?.HandleExceptionAsync.Invoke(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; - - default: - logger?.LogError(exception, "Unhandled exception occurred."); - context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - message = "An unexpected error occurred."; - break; - } - - await context.Response.WriteAsync(JsonSerializer.Serialize(new - { - message - })); - } }