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 <noreply@anthropic.com>
This commit is contained in:
Spencer Twaddle
2026-05-02 15:57:13 -05:00
parent 9b1b704ea1
commit cd42a8ec2c
2 changed files with 22 additions and 0 deletions
+1
View File
@@ -126,6 +126,7 @@ using (var scope = app.Services.CreateScope())
} }
app.UseForwardedHeaders(); app.UseForwardedHeaders();
app.UseMiddleware<ErrorHandlingMiddleware>();
app.UseDefaultFiles(); app.UseDefaultFiles();
app.UseStaticFiles(); app.UseStaticFiles();
@@ -0,0 +1,21 @@
using System.Text.Json;
namespace Budget.Api.Services;
public class ErrorHandlingMiddleware(RequestDelegate next, ILogger<ErrorHandlingMiddleware> 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." }));
}
}
}