الانتقال إلى المحتوى
.NETASP.NET Core· 8 دقائق للقراءة

Stop Wrapping Every Endpoint in try/catch: Centralized Errors with ProblemDetails

One exception handler at the top of the pipeline turns every failure into a standard RFC 9457 response, covers endpoints nobody wrapped, and keeps internals out of the body.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

The mobile team files a bug against the orders API: errors arrive in four shapes. The orders endpoints return {"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

The belief: an exception that escapes an endpoint is a disaster, so every handler needs its own try/catch that turns failures into a proper error response.

The instinct comes from good places. C# courses teach 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.

The last point is the real problem, and it has a better fix than a catch block in every endpoint.

What actually happens

An exception ends the request, not the server

When an endpoint throws, ASP.NET Core catches it around that request. The server logs it, the client gets a 500, and every other request carries on. Nothing crashes. The empty body is just what you get when nobody told the app how to describe errors.

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

come from RFC 9457, which replaced RFC 7807. An error is a JSON object sent as 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

"Order not found" and "quantity out of range" are normal outcomes. Return them as results, 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

C# Program.cs
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();

On .NET 10, the second version answers an unknown order with a 404 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.

For an exception you want to map to a specific status, add one handler and register it with builder.Services.AddExceptionHandler<ConcurrencyExceptionHandler>():

C# ConcurrencyExceptionHandler.cs
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." }        });    }}

Handlers run in the order you register them, until one returns true. If none does, the middleware falls back to its default 500.

try/catch everywhere vs one handler

try/catch in every endpointException handler with ProblemDetails
Response shapeWhatever each author wroteOne RFC 9457 shape, application/problem+json
A new endpointUnprotected until someone adds a catchCovered as soon as it's mapped
Exception detailsOften leaked through ex.MessageKept in the log; the client gets a traceId
Errors outside endpointsNot covered: routing 404s, middleware failuresCovered by the same two middleware
Mapping to status codesRepeated in each catchOne handler per kind of exception

How to apply it in your project

  1. Add the three linesCall builder.Services.AddProblemDetails(), then make app.UseExceptionHandler() the first middleware and add app.UseStatusCodePages() right after it.
  2. Delete formatting-only catch blocksSearch for catch (Exception in endpoints. Remove the ones that only build an error response, and keep the ones that retry, clean up or rethrow.
  3. Return results for expected failuresUse Results.NotFound(), Results.Conflict() or a validation problem instead of throwing for outcomes you expect. They get the same problem details shape.
  4. Test the error contractWrite an integration test that hits a failing endpoint and checks the application/problem+json content 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/catch to stay safe.
  • AddProblemDetails, UseExceptionHandler first in the pipeline and UseStatusCodePages give 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.

📚 المصادر

  1. Handle errors in ASP.NET Core — Microsoft Learn
  2. Handle errors in ASP.NET Core APIs — Microsoft Learn
  3. RFC 9457: Problem Details for HTTP APIs — RFC Editor

التعليقات (0)