DigitalData.Core/DigitalData.Core.Exceptions.Middleware/GlobalExceptionHandlerMiddleware.cs

53 lines
2.0 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 is not null)
await _options.DefaultHandler.HandleExceptionAsync(context, ex, _logger);
if (_options?.Handlers.TryGetValue(ex.GetType(), out var handler) ?? false)
await handler.HandleExceptionAsync(context, ex, _logger);
}
}
}