From cd42a8ec2c5a955d91f3ad7865eb371717d8b5df Mon Sep 17 00:00:00 2001 From: Spencer Twaddle <7374698+stwaddle@users.noreply.github.com> Date: Sat, 2 May 2026 15:57:13 -0500 Subject: [PATCH] Add ErrorHandlingMiddleware for consistent JSON error responses Catches all unhandled exceptions, logs them, and returns { "error": "An unexpected error occurred." } with HTTP 500. Registered before all other middleware so nothing leaks through. Co-Authored-By: Claude Sonnet 4.6 --- src/Budget.Api/Program.cs | 1 + .../Services/ErrorHandlingMiddleware.cs | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 src/Budget.Api/Services/ErrorHandlingMiddleware.cs diff --git a/src/Budget.Api/Program.cs b/src/Budget.Api/Program.cs index b07d8bc..2ffe153 100644 --- a/src/Budget.Api/Program.cs +++ b/src/Budget.Api/Program.cs @@ -126,6 +126,7 @@ using (var scope = app.Services.CreateScope()) } app.UseForwardedHeaders(); +app.UseMiddleware(); app.UseDefaultFiles(); app.UseStaticFiles(); diff --git a/src/Budget.Api/Services/ErrorHandlingMiddleware.cs b/src/Budget.Api/Services/ErrorHandlingMiddleware.cs new file mode 100644 index 0000000..c86b9c2 --- /dev/null +++ b/src/Budget.Api/Services/ErrorHandlingMiddleware.cs @@ -0,0 +1,21 @@ +using System.Text.Json; + +namespace Budget.Api.Services; + +public class ErrorHandlingMiddleware(RequestDelegate next, ILogger logger) +{ + public async Task InvokeAsync(HttpContext context) + { + try + { + await next(context); + } + catch (Exception ex) + { + logger.LogError(ex, "Unhandled exception"); + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(JsonSerializer.Serialize(new { error = "An unexpected error occurred." })); + } + } +}