wasAsked.

What is the correct way to implement global exception handling and Problem Details in ASP.NET Core?

Razorpay · Full Stack Developer · 3-4-years · technical

Published

Year not specified · .NET, ASP.NET Core, Software Engineering

Community answers

Posted by wasAsked editorial collection

Handle unexpected exceptions once near the HTTP boundary, log the full server-side error with a correlation/trace ID, and return a safe RFC 7807 Problem Details response. Map expected domain outcomes explicitly rather than throwing for normal control flow. Example: builder.Services.AddProblemDetails(); app.UseExceptionHandler(); Return stable status/type/title fields and validation errors, but never stack traces, SQL, secrets, or internal host names. Distinguish 400 validation, 401 authentication, 403 authorization, 404 absence, 409 conflicts, and 500 unexpected failures. Preserve cancellation semantics, avoid catching exceptions only to rethrow incorrectly, and add tests confirming production responses do not leak sensitive details.

Backbencher Developer · · 0 likes

Goals: every error becomes a consistent, safe response; clients can parse it; developers can trace it. 1. Use the built-in Problem Details support (.NET 7+) builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = ctx => ctx.ProblemDetails.Extensions["traceId"] = Activity.Current?.Id ?? ctx.HttpContext.TraceIdentifier); builder.Services.AddExceptionHandler<GlobalExceptionHandler>(); app.UseExceptionHandler(); // first in the pipeline app.UseStatusCodePages(); // Problem Details for empty 404/405 responses too 2. Map exceptions centrally with IExceptionHandler (.NET 8+) public sealed class GlobalExceptionHandler(IProblemDetailsService problems, ILogger<GlobalExceptionHandler> log) : IExceptionHandler { public async ValueTask<bool> TryHandleAsync(HttpContext ctx, Exception ex, CancellationToken ct) { var (status, title) = ex switch { NotFoundException => (404, "Resource not found"), ConflictException => (409, "Conflict"), ValidationException => (400, "Validation failed"), _ => (500, "An unexpected error occurred") }; if (status == 500) log.LogError(ex, "Unhandled exception"); ctx.Response.StatusCode = status; return await problems.TryWriteAsync(new() { HttpContext = ctx, Exception = ex, ProblemDetails = { Status = status, Title = title } }); } } 3. Rules - Never return stack traces or exception messages for 500 errors in production; use the developer exception page only in Development. - Validation errors use ValidationProblemDetails with a field-to-messages dictionary ([ApiController] does this automatically for model-state errors). - Do not use exceptions for normal control flow; return results (TypedResults.NotFound()) where an outcome is expected. Reserve exceptions for exceptional cases. - Treat client disconnects (OperationCanceledException with RequestAborted) differently from errors — do not log them as failures. - Log unhandled exceptions once, with structured context. - Include the traceId so support can correlate a user's error with logs. 4. Test it Integration tests that trigger each mapped exception and assert status code, content type application/problem+json, and that no sensitive details leak.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics