using Microsoft.AspNetCore.Mvc; using System.Net; namespace FiscalFlow.API.Middleware; public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (Exception ex) { _logger.LogError(ex, "An unhandled exception occurred"); await HandleExceptionAsync(context, ex); } } private static Task HandleExceptionAsync(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; var (statusCode, errorCode, message) = exception switch { UnauthorizedAccessException _ => ( (int)HttpStatusCode.Unauthorized, "UNAUTHORIZED", "Authentication required" ), InvalidOperationException _ => ( (int)HttpStatusCode.BadRequest, "INVALID_OPERATION", exception.Message ), KeyNotFoundException _ => ( (int)HttpStatusCode.NotFound, "NOT_FOUND", "Resource not found" ), _ => ( (int)HttpStatusCode.InternalServerError, "INTERNAL_ERROR", "An unexpected error occurred" ) }; context.Response.StatusCode = statusCode; var response = new { success = false, error = new { code = errorCode, message }, meta = new { request_id = context.TraceIdentifier, timestamp = DateTime.UtcNow.ToString("O") } }; return context.Response.WriteAsJsonAsync(response); } }