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." })); + } + } +}