feat(logging): implement GlobalExceptionHandler for centralized error handling

This commit is contained in:
Stevan Freeborn
2026-01-04 22:08:05 -06:00
parent d510939a54
commit e41338eda2
2 changed files with 35 additions and 0 deletions
@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
namespace GroundsForSupport.Server.Logging;
internal sealed class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> _logger = logger;
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken
)
{
_logger.LogError(exception, "Exception occurred: {Message}", exception.Message);
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "Server Error",
Detail = "An internal error occurred."
};
httpContext.Response.StatusCode = problemDetails.Status.Value;
await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
return true;
}
}
+4
View File
@@ -1,6 +1,7 @@
using System.Text.Json; using System.Text.Json;
using GroundsForSupport.Server.Data; using GroundsForSupport.Server.Data;
using GroundsForSupport.Server.Logging;
using GroundsForSupport.Server.Payments.Endpoints; using GroundsForSupport.Server.Payments.Endpoints;
using GroundsForSupport.Server.Payments.Stripe; using GroundsForSupport.Server.Payments.Stripe;
using GroundsForSupport.Server.RateLimiting; using GroundsForSupport.Server.RateLimiting;
@@ -13,6 +14,7 @@ builder.Services.AddOpenApi();
builder.Services.AddValidation(); builder.Services.AddValidation();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails(); builder.Services.AddProblemDetails();
builder.Services.AddHttpClient(); builder.Services.AddHttpClient();
@@ -38,6 +40,8 @@ builder.Services.ConfigureHttpJsonOptions(
var app = builder.Build(); var app = builder.Build();
app.UseExceptionHandler();
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {
app.MapOpenApi(); app.MapOpenApi();