using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace DigitalData.Core.Exceptions.Middleware;
///
/// 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.
///
public class GlobalExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger? _logger;
private readonly GlobalExceptionHandlerOptions? _options;
///
/// Initializes a new instance of the class.
///
/// The next middleware in the request pipeline.
/// The logger instance for logging exceptions.
public GlobalExceptionHandlerMiddleware(RequestDelegate next, ILogger? logger = null, IOptions? options = null)
{
_next = next;
_logger = logger;
_options = options?.Value;
}
///
/// Invokes the middleware to handle the HTTP request.
///
/// The HTTP context of the current request.
/// A task that represents the asynchronous operation.
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);
}
}
}