using System.Net; using System.Text.Json; namespace HelpDesk.API.Middleware; public class ExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public ExceptionMiddleware(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: {Message}", ex.Message); await HandleExceptionAsync(context, ex); } } private static async Task HandleExceptionAsync(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; var (statusCode, message) = exception switch { ArgumentException argEx => (HttpStatusCode.BadRequest, argEx.Message), KeyNotFoundException keyEx => (HttpStatusCode.NotFound, keyEx.Message), UnauthorizedAccessException => (HttpStatusCode.Unauthorized, "Unauthorized access."), InvalidOperationException opEx => (HttpStatusCode.BadRequest, opEx.Message), _ => (HttpStatusCode.InternalServerError, "An unexpected error occurred.") }; context.Response.StatusCode = (int)statusCode; var response = new { error = message, statusCode = (int)statusCode }; await context.Response.WriteAsync(JsonSerializer.Serialize(response, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })); } }