In ASP.NET Core 10, how do the developer exception page and UseExceptionHandler differ, and which one handles an unhandled exception in each environment?
answer
- one page for developers, one for users
- WebApplication adds it in Development
- IHostEnvironment.IsDevelopment() guard
- re-executes at the error path, method kept
- IExceptionHandlerPathFeature: Error and Path
basics
~20 sThe developer exception page shows the stack trace, headers and routing data and is added automatically in Development; UseExceptionHandler catches the exception in production and runs a safe error path, delegate or ProblemDetails writer instead.
solid answer
~40 sSince minimal hosting, `WebApplication` inserts `UseDeveloperExceptionPage()` at the front of the pipeline whenever the environment is Development, so you do not call it yourself. It renders an HTML page with the stack trace, query, cookies, headers and route values for a browser, and plain text (or a ProblemDetails body with an `exception` extension when `AddProblemDetails()` is registered) for any other client. It must never serve production traffic. For production you call `app.UseExceptionHandler("/Error")`, which the templates guard with `if (!app.Environment.IsDevelopment())`. That middleware catches the exception, clears the response, sets 500, stores `IExceptionHandlerPathFeature` and re-executes the request at the error path with the original HTTP method, so the error endpoint can log and answer without leaking internals.
code
csharp · 23 linesvar builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Development: WebApplication already added the developer exception page.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/error", createScopeForErrors: true);
app.UseHsts();
}
app.MapGet("/catalogue/books/{isbn}", (string isbn, CatalogueService catalogue) =>
catalogue.GetBook(isbn));
// Map (not MapGet): the failed request is re-executed with its original method.
app.Map("/error", (HttpContext context) =>
{
var failure = context.Features.Get<IExceptionHandlerPathFeature>();
return Results.Problem(
title: "The catalogue could not complete this request.",
instance: failure?.Path);
});
app.Run();go deeper
Recall that WebApplication adds the developer page only in Development and that production uses UseExceptionHandler with a safe error endpoint.
Explain what the handler middleware does on an exception: clear, set 500, store IExceptionHandlerPathFeature, re-execute with the same method, and why Map beats MapGet for the error endpoint.
Show you keep stack traces out of production, use createScopeForErrors when the failed request's scoped services may be poisoned, and know the response-started limit.
Frame error output as a policy: what each environment may reveal, who owns the error endpoint, and how the same contract covers HTML pages and API clients.
## Two middlewares, two audiences ASP.NET Core ships two pieces of middleware that turn an **unhandled exception** (one that escapes an endpoint, a filter or later middleware) into an HTTP response. They serve different readers: - The **developer exception page** (`UseDeveloperExceptionPage`) is for the person debugging the app. It shows everything it can find. - The **exception handler middleware** (`UseExceptionHandler`) is for real users and API clients. It shows only what you decide to show. Both live in the `Microsoft.AspNetCore.Diagnostics` assembly, which is part of the shared framework, so no package reference is needed. ## The developer exception page With `WebApplication.CreateBuilder` (the minimal hosting model every current template uses) you never write `app.UseDeveloperExceptionPage()`. When the app is built, `WebApplication` checks `IHostEnvironment.IsDevelopment()` (driven by `ASPNETCORE_ENVIRONMENT` or `DOTNET_ENVIRONMENT`) and, if true, inserts the page at the very front of the pipeline. What it writes depends on the request's `Accept` header: - A browser that accepts `text/html` gets an HTML page with tabs for the **stack trace**, **query string**, **cookies**, **headers** and **routing** (endpoint and route values). `DeveloperExceptionPageOptions.SourceCodeLineCount` (default 6) controls how many source lines surround each frame when symbols and source are present. - Any other client gets the exception as **plain text** plus the request headers, or, when `AddProblemDetails()` has registered `IProblemDetailsService`, a **ProblemDetails JSON body** whose `exception` extension carries the details, headers, path, endpoint and route values. That is exactly why it must stay out of production: it publishes stack traces, header values and internal type names to whoever triggered the error. ## The exception handler middleware `app.UseExceptionHandler(...)` wraps everything registered after it. When an exception escapes and the response has **not started**, it does this: 1. Clears the response (status, headers, any buffered body) and resets the selected endpoint. 2. Sets the status to 500 (or what `ExceptionHandlerOptions.StatusCodeSelector` returns). 3. Stores an `ExceptionHandlerFeature` as both `IExceptionHandlerFeature` and `IExceptionHandlerPathFeature`. 4. Gives registered `IExceptionHandler` services a chance, then runs the configured fallback: the error **path**, a **delegate** pipeline, or `IProblemDetailsService`. 5. Adds no-cache headers so a proxy never caches the error. The overloads choose the fallback: `UseExceptionHandler("/Error")` re-executes the request at that path, `UseExceptionHandler("/Error", createScopeForErrors: true)` also gives the re-execution a fresh DI scope (the Blazor Web App template does this), `UseExceptionHandler(errorApp => ...)` runs a branch you build, and `UseExceptionHandler()` with no arguments relies on DI-configured options or on `AddProblemDetails()`. Re-execution keeps the **original HTTP method**. An error endpoint mapped with `MapGet` or an MVC action marked `[HttpGet]` therefore never runs for a failed POST; map it with `app.Map(...)` or leave the action without verb attributes. ## Reading the error in the handler The error endpoint reads `HttpContext.Features.Get<IExceptionHandlerPathFeature>()`: | Member | What it holds | |---|---| | `Error` | the exception that escaped | | `Path` | the original, un-escaped request path | | `Endpoint` | the endpoint that was selected before the failure | | `RouteValues` | the route values of the original request | `IExceptionHandlerFeature` exposes the same members; the path feature exists so code can ask specifically for `Path`. ## Choosing per environment | | Developer exception page | Exception handler middleware | |---|---|---| | Added by | `WebApplication`, Development only | your `Program.cs` | | Audience | the developer | users and API clients | | Shows stack trace | yes | only if your handler writes it (it should not) | | Output | HTML, plain text or ProblemDetails | whatever your path, delegate, handler or ProblemDetails writer produces | The templates put `UseExceptionHandler` inside `if (!app.Environment.IsDevelopment())`. Called unconditionally, it would sit inside the developer page and catch the exception first, so in Development the developer page would not appear for any exception the handler deals with. ## Common mistakes - Calling `UseDeveloperExceptionPage()` by hand in a `WebApplication` app, or enabling it in production "just to debug". - Expecting `UseExceptionHandler("/Error")` to redirect: it re-executes internally and the client sees a 500, not a 302. - Expecting either middleware to rescue a response whose headers were already sent: once `Response.HasStarted` is true, the exception handler logs and rethrows. - Writing `exception.Message` or `exception.ToString()` into the production error response: that leaks the same internals the developer page shows, only to strangers. - Testing the production path only by reading code: run the app with `ASPNETCORE_ENVIRONMENT=Production` locally and trigger a failure, because in Development the developer page hides what users would see.
- Why does the error endpoint behind UseExceptionHandler("/error") sometimes never run for POST requests?The middleware re-executes the failed request at the error path with its original HTTP method. An endpoint mapped with `MapGet`, or an MVC action carrying `[HttpGet]`, matches only GET, so a failed POST finds no endpoint, routing produces an empty 404 and the middleware rethrows the original exception wrapped in an `InvalidOperationException`. Map the error endpoint with `app.Map` or leave the action without verb attributes.
- What does createScopeForErrors: true change in UseExceptionHandler?It sets `ExceptionHandlerOptions.CreateScopeForErrors`, so the middleware creates a new DI scope and swaps it into `HttpContext.RequestServices` while the error path runs, then restores the original. Scoped services the failed request had already used, such as a DbContext left in a broken state, are not reused by the error page. The default is false; the Blazor Web App template turns it on.
- How does the developer exception page answer an API client that sends Accept: application/json?It skips the HTML page. If `IProblemDetailsService` is registered through `AddProblemDetails()`, it writes a ProblemDetails body whose title is the exception type, whose detail is the message and whose `exception` extension holds the details, headers, path, endpoint and route values. Without that service it writes the exception and the request headers as plain text.
- You must call app.UseDeveloperExceptionPage() in Program.cs or the page never appears.
- UseExceptionHandler("/error") answers the client with a 302 redirect to the error page.
- The error endpoint can be MapGet because the handler always re-executes the request as GET.
- Turning on the developer exception page in production is fine if the API needs authentication.
- UseExceptionHandler can still replace a response whose headers have already been sent.