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.
This commit is contained in:
Developer 02 2025-05-19 15:21:11 +02:00
parent 14013bc7b7
commit b8995da5ea

View File

@ -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;
/// <summary>
/// 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);
}
}
/// <summary>
/// Handles exceptions by logging them and writing an appropriate JSON response.
/// </summary>
/// <param name="context">The HTTP context of the current request.</param>
/// <param name="exception">The exception that occurred.</param>
/// <param name="logger">The logger instance for logging the exception.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
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
}));
}
}