Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 52 ยท Middleware and the Request Pipeline

Error Handling and Problem Details

Handle errors in ASP.NET Core with UseExceptionHandler, IExceptionHandler, status code pages and RFC 9457 ProblemDetails, and know what the developer exception page shows.

Sooner or later every endpoint throws. A database is down, a value is missing, a bug slips through. What matters is what the client sees: a half-written page, a raw stack trace that leaks internals, or a clean, predictable error response that a program can understand.

ASP.NET Core gives you a small set of tools for this: middleware that catches exceptions, a hook for turning exceptions into responses, a standard JSON error shape called ProblemDetails, and pages for bare status codes like 404. This lesson shows each tool and how they fit together. It builds on HttpContext (especially the rule that a started response cannot change) and on the middleware pipeline.

What happens to an unhandled exception

If an exception escapes an endpoint and no middleware catches it, Kestrel logs it and sends an empty 500 Internal Server Error (or, if the response had already started, simply drops the connection). That is safe, but unhelpful. The fix is to place an exception-handling middleware at the very beginning of the pipeline. Middleware registered later runs inside it, so any exception thrown further in bubbles up to it, like an exception climbing out of nested try blocks.

flowchart LR
    REQ["Request"] --> EH["UseExceptionHandler"]
    EH --> OTHER["other middleware"]
    OTHER --> EP["Endpoint throws"]
    EP -. "exception bubbles up" .-> EH
    EH --> RESP["500 + clean error body"]

The exception handler wraps everything that comes after it, so register it first.

UseExceptionHandler

UseExceptionHandler catches the exception, clears the partial response, runs your handler and keeps the 500 status unless you change it. The simplest form takes a small pipeline branch:

C#
app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "Something went wrong." });
    });
});

Inside the handler, context.Features.Get<IExceptionHandlerFeature>() returns the original exception (.Error) and the path where it happened. You should log it there and decide what, if anything, to tell the client. Never send ex.Message or a stack trace to the outside world in production: messages can reveal table names, file paths or secrets.

Status code pages

Not every error is an exception. A request for a URL nobody mapped produces a 404 with an empty body, and Results.StatusCode(401) produces a bare 401. UseStatusCodePages fills these empty error responses with a body. It only acts on responses that have an error status (400 to 599) and no body yet.

The next example wires both pieces together and calls a good route, a throwing route and an unknown route.

C# Exception handler and status code pages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at what the client saw for /boom: a generic message, with the secret detail only in our server-side log. The /forbidden and /nowhere responses had no body of their own, so the status code page wrote one. The route /ok was untouched.

There are also redirect variants, UseStatusCodePagesWithRedirects and UseStatusCodePagesWithReExecute. Re-execution runs another endpoint of your app (for example /errors/{0}) while keeping the original status code, which is handy for HTML sites with branded 404 pages. For JSON APIs, ProblemDetails (next) is the better fit.

ProblemDetails: a standard error shape

If every endpoint invented its own error JSON, every client would need custom parsing. Problem Details is an IETF standard (RFC 9457, which updated RFC 7807) that defines a common JSON object served as application/problem+json:

Field Meaning
type A URI that identifies the kind of problem (often a documentation link).
title A short, human-readable summary that stays the same for the same type.
status The HTTP status code, repeated for convenience.
detail A sentence about this specific occurrence.
instance A URI for this occurrence (often the request path).
extensions Any extra fields, such as traceId or a list of validation errors.

ASP.NET Core has a class ProblemDetails for this and a service, IProblemDetailsService, that writes it. Register the service with one line:

C#
builder.Services.AddProblemDetails();

Once registered, the framework's own error producers use it automatically. UseExceptionHandler() (called with no arguments), UseStatusCodePages() and the developer exception page all emit ProblemDetails for API-style requests, and the traceId extension is added for you. You can also return one yourself from an endpoint with Results.Problem(...) or TypedResults.Problem(...).

AddProblemDetails also lets you customize every problem document in one place with options.CustomizeProblemDetails = ctx => { ... }. Add a correlation id, hide the detail in production or attach a link to your docs there.

IExceptionHandler: mapping exceptions to responses

A single catch-all handler is rarely enough. A "not found" exception from your domain should become a 404, a validation exception a 400, and only truly unexpected failures a 500. The IExceptionHandler interface (available since .NET 8) is built for this. It has one method:

C#
ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct);

Return true when you handled the exception and wrote the response. Return false to let the next handler try. Register handlers with AddExceptionHandler<T>(); they run in the order registered, and the first one returning true wins. If none handles it, the default behavior (ProblemDetails with status 500 when AddProblemDetails is on) applies. Handlers are created as singletons, so inject only singleton-safe services.

The example below defines a small domain exception, one handler that maps it, and a fallback. Each response is a ProblemDetails document.

C# IExceptionHandler and ProblemDetails

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The ordering of output tells the story. /products/99 threw our domain exception, so NotFoundExceptionHandler returned a 404 ProblemDetails. /crash was not handled by our class (it returned false), so the built-in fallback wrote a generic 500 ProblemDetails without the real message. /custom never threw: the endpoint returned Results.Problem directly. /missing-route had an empty 404, which UseStatusCodePages turned into ProblemDetails.

Using exceptions for expected outcomes like "not found" is a style choice. For hot paths, returning Results.NotFound() or Results.Problem() directly is cheaper, because throwing exceptions in .NET is slow compared to returning values. Reserve exceptions for the unexpected, and use handlers as the safety net.

The developer exception page

During development you do want details. WebApplication automatically adds the developer exception page when the environment is Development. It shows the exception type, message, stack trace, query string, headers and cookies of the failed request. Because it exposes this, it must never run in production. The environment comes from ASPNETCORE_ENVIRONMENT (see environments and secrets), and the usual pattern is:

C#
if (app.Environment.IsDevelopment())
{
    // detailed pages are added automatically by WebApplication
}
else
{
    app.UseExceptionHandler();
    app.UseHsts();
}

The next example runs the same failing endpoint in both environments to show the difference. The runner defaults to Production; the second app is created with the Development environment name.

C# Development versus Production error output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In Production the response is empty (or ProblemDetails with no detail, once you add the handlers above); in Development the response carries the message and type. That asymmetry is exactly what you want, and it is why a missing UseExceptionHandler in production is a security smell as well as a usability one.

A practical checklist

  1. Register AddProblemDetails() so every error producer shares one format.
  2. Call UseExceptionHandler() first in the pipeline (in non-development environments, or always if you prefer the same behavior everywhere).
  3. Add one IExceptionHandler per family of exceptions you want mapped to a status code, ending with the built-in fallback for the rest.
  4. Add UseStatusCodePages() so bare 404s and 401s are not empty.
  5. Log the exception where you handle it, with the trace id, and never put internals in the response.
  6. Remember that after Response.HasStarted no handler can change the status; stream carefully and prefer to validate before writing.

You will use this setup again in the Todo API project, and the validation lesson shows how validation failures become 400 ProblemDetails with an errors object.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should UseExceptionHandler be placed in the pipeline?

    Middleware runs nested like try blocks. Only middleware registered after the handler is covered by it, so it belongs first.
  2. 2. What does an IExceptionHandler return to say it handled the exception?

    TryHandleAsync returns true when it wrote the response. Returning false passes the exception to the next registered handler and finally to the default behavior.
  3. 3. Which media type does a ProblemDetails response normally use?

    RFC 9457 defines application/problem+json (and application/problem+xml) as the media types for problem documents.
  4. 4. A route does not exist and the response is an empty 404. Which feature fills in a body for it?

    A missing route throws nothing; it just sets 404 with no body. UseStatusCodePages writes a body for error responses that have none.
  5. 5. Why is the developer exception page enabled only in the Development environment?

    The page shows internals of the failed request and the exception. That is helpful to you and dangerous to attackers.

Summary

  • An unhandled exception becomes an empty 500; put UseExceptionHandler first to turn it into a clean response.
  • UseStatusCodePages fills empty 4xx and 5xx responses such as unmapped-route 404s.
  • ProblemDetails (RFC 9457, application/problem+json) is the standard JSON error shape; AddProblemDetails() makes the framework produce it everywhere.
  • IExceptionHandler maps exception types to status codes; return true when handled, false to continue down the chain.
  • The developer exception page is automatic in Development only; never expose messages or stack traces in production.
  • Log details on the server, include a trace id in the response, and prefer returning results over throwing for expected outcomes.

Next: Static Files, Default Documents and CORS