DigitalData.Core/DigitalData.Core.Exceptions.Middleware/GlobalExceptionHandlerMiddleware.cs
Developer 02 b8995da5ea 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.
2025-05-19 15:21:11 +02:00

53 lines
1.9 KiB
C#

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace DigitalData.Core.Exceptions.Middleware;
/// <summary>
/// Middleware for handling exceptions globally in the application.
/// Captures exceptions thrown during the request pipeline execution,
/// logs them, and returns an appropriate HTTP response with a JSON error message.
/// </summary>
public class GlobalExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<GlobalExceptionHandlerMiddleware>? _logger;
private readonly GlobalExceptionHandlerOptions? _options;
/// <summary>
/// Initializes a new instance of the <see cref="GlobalExceptionHandlerMiddleware"/> class.
/// </summary>
/// <param name="next">The next middleware in the request pipeline.</param>
/// <param name="logger">The logger instance for logging exceptions.</param>
public GlobalExceptionHandlerMiddleware(RequestDelegate next, ILogger<GlobalExceptionHandlerMiddleware>? logger = null, IOptions<GlobalExceptionHandlerOptions>? options = null)
{
_next = next;
_logger = logger;
_options = options?.Value;
}
/// <summary>
/// Invokes the middleware to handle the HTTP request.
/// </summary>
/// <param name="context">The HTTP context of the current request.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context); // Continue down the pipeline
}
catch (Exception ex)
{
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);
}
}
}