
Stop Wrapping Every Endpoint in try/catch: Centralized Errors with ProblemDetails
- كاتب موثّق
- .NET 10
محتويات المقال
{"error": "..."}, payments returns a plain string, the newest endpoint returns an empty 500, and one response contains a full database error message, user and table names included. Every endpoint author handled errors. Each did it differently, and the one who forgot didn't handle them at all.
The common misconception
try/catch that turns failures into a proper error response.
try/catch as "error handling". In a console app, an unhandled exception really does kill the process. In Development, a failing endpoint shows a page full of stack trace, which looks like something users must never see. And in production, an endpoint that throws without any handler configured returns a 500 with an empty body, so wrapping the code seems like the only way to send something useful.
What actually happens
An exception ends the request, not the server
One middleware at the top of the pipeline
UseExceptionHandler is that wraps everything registered after it, endpoints included. Combined with builder.Services.AddProblemDetails(), it catches any exception thrown further down, logs it, and writes a standard error response in place of the empty 500. Its partner, UseStatusCodePages, fills in error responses that have no body yet, such as a 404 from routing or a Results.NotFound(). Because it guards only what comes after it, register the exception handler first.
ProblemDetails is a standard, not a Microsoft format
application/problem+json, with type, title, status, detail and instance members, plus any extension members you add. ASP.NET Core adds a traceId extension. The RFC also advises against putting implementation details such as stack dumps in the response, which is exactly what ex.Message tends to do.
Expected failures aren't exceptions
Results.NotFound() or a validation problem, and the problem details service shapes them like every other error. For exceptions you can't avoid but can classify, such as an EF Core concurrency conflict, write one IExceptionHandler that maps them to a status code for the whole app.
The orders endpoint, before and after
var builder = WebApplication.CreateBuilder(args);builder.Services.AddSingleton<OrderStore>();var app = builder.Build();app.MapGet("/orders/{id:int}", async (int id, OrderStore store) =>{ try { var order = await store.FindAsync(id); return order is null ? Results.NotFound() : Results.Ok(order); } catch (Exception ex) { // its own error shape, and ex.Message can expose SQL or file paths return Results.Json(new { error = ex.Message }, statusCode: 500); }}); // ...repeated in every endpoint, until one forgetsapp.Run();var builder = WebApplication.CreateBuilder(args);builder.Services.AddProblemDetails();builder.Services.AddSingleton<OrderStore>();var app = builder.Build();app.UseExceptionHandler(); // first: catches what everything after it throwsapp.UseStatusCodePages(); // empty 4xx/5xx responses get a ProblemDetails bodyapp.MapGet("/orders/{id:int}", async (int id, OrderStore store) => await store.FindAsync(id) is { } order ? Results.Ok(order) : Results.NotFound());app.Run();application/problem+json body: "title": "Not Found", "status": 404 and a traceId. When the store throws, the client gets a 500 with "title": "An error occurred while processing your request." and no exception text, while the full exception goes to the log. A URL that matches no endpoint gets the same 404 shape. That's three kinds of failure, one format, and no catch anywhere.
builder.Services.AddExceptionHandler<ConcurrencyExceptionHandler>():
using Microsoft.AspNetCore.Diagnostics;using Microsoft.EntityFrameworkCore;public sealed class ConcurrencyExceptionHandler( IProblemDetailsService problemDetails, ILogger<ConcurrencyExceptionHandler> logger) : IExceptionHandler{ public async ValueTask<bool> TryHandleAsync( HttpContext context, Exception exception, CancellationToken ct) { if (exception is not DbUpdateConcurrencyException) return false; // not ours: the next handler, or the default 500 logger.LogWarning(exception, "Conflict on {Path}", context.Request.Path); context.Response.StatusCode = StatusCodes.Status409Conflict; return await problemDetails.TryWriteAsync(new() { HttpContext = context, ProblemDetails = { Title = "The order was changed by someone else." } }); }}true. If none does, the middleware falls back to its default 500.
try/catch everywhere vs one handler
try/catch in every endpoint | ||
|---|---|---|
application/problem+json | ||
ex.Message | traceId | |
How to apply it in your project
Add the three lines Call builder.Services.AddProblemDetails(), then makeapp.UseExceptionHandler()the first middleware and addapp.UseStatusCodePages()right after it.Delete formatting-only catch blocks Search for catch (Exceptionin endpoints. Remove the ones that only build an error response, and keep the ones that retry, clean up or rethrow.Return results for expected failures Use Results.NotFound(),Results.Conflict()or a validation problem instead of throwing for outcomes you expect. They get the same problem details shape.Test the error contract Write an integration test that hits a failing endpoint and checks the application/problem+jsoncontent type, the status code and that the body contains no exception message.
Key takeaways
An unhandled exception ends one request with a 500; it doesn't crash the server, so endpoints don't need a try/catchto stay safe.AddProblemDetails,UseExceptionHandlerfirst in the pipeline andUseStatusCodePagesgive every error the same RFC 9457 shape, including endpoints nobody wrapped.Return results for expected failures, and map unavoidable exceptions to status codes in one IExceptionHandler.In .NET 10, exceptions a handler marks as handled aren't logged by the middleware, so log them in the handler.
التعليقات (0)