In ASP.NET Core there are three common approaches; the first is the recommended one for .NET 8 and later. 1. IExceptionHandler with Problem Details (.NET 8+, recommended) public sealed class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger, IProblemDetailsService problemDetails) : IExceptionHandler { public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct) { var (status, title) = exception switch { KeyNotFoundException => (StatusCodes.Status404NotFound, "Resource not found"), ArgumentException => (StatusCodes.Status400BadRequest, "Invalid request"), UnauthorizedAccessException => (StatusCodes.Status403Forbidden, "Access denied"), _ => (StatusCodes.Status500InternalServerError, "An unexpected error occurred") }; if (status >= 500) logger.LogError(exception, "Unhandled exception"); context.Response.StatusCode = status; return await problemDetails.TryWriteAsync(new ProblemDetailsContext { HttpContext = context, Exception = exception, ProblemDetails = { Status = status, Title = title } }); } } // Program.cs builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = c => c.ProblemDetails.Extensions["traceId"] = Activity.Current?.Id ?? c.HttpContext.TraceIdentifier); builder.Services.AddExceptionHandler<GlobalExceptionHandler>(); app.UseExceptionHandler(); // early in the pipeline app.UseStatusCodePages(); // Problem Details for empty error responses (404, 405) Several IExceptionHandler implementations can be registered; they run in order until one returns true. 2. Custom middleware (works in all versions) A middleware wraps await next(context) in try/catch, logs the exception, checks Response.HasStarted, and writes a JSON Problem Details response. Register it first with app.UseMiddleware<ExceptionMiddleware>(). 3. MVC exception filters IExceptionFilter or IAsyncExceptionFilter handle exceptions thrown in controller actions and filters only — not in middleware or minimal API endpoints. Useful for MVC-specific mapping, but middleware-based handling covers more. Best practices - Register the handler early in the pipeline so it catches errors from everything after it. - Never expose stack traces or internal messages in production; show the developer exception page only in Development. - Use a consistent response format (Problem Details) and appropriate status codes. - Log once, with context, and include a trace ID in the response for support. - Treat client cancellations (OperationCanceledException when the request is aborted) separately — they are not server errors. - Prefer returning results for expected cases (not found, validation) rather than throwing exceptions for normal control flow. - Test the behaviour with integration tests (WebApplicationFactory) to confirm the status code, content type (application/problem+json) and body.
Ravindra Wadile · · 0 likes