.NET › ASP.NET Core Middleware & Request Pipeline

What is the purpose of UseExceptionHandler and UseDeveloperExceptionPage middleware, and how should they differ between environments?

Intermediate

Answer

UseDeveloperExceptionPage shows detailed stack traces and exception information directly in the browser, intended only for local development since it leaks sensitive implementation details. UseExceptionHandler is the production-safe alternative, catching unhandled exceptions and routing to a generic error page or a custom error-handling endpoint without exposing internal details to end users, typically registered conditionally based on the hosting environment.
if (app.Environment.IsDevelopment()) {
    app.UseDeveloperExceptionPage();
} else {
    app.UseExceptionHandler("/error");
    app.UseHsts();
}
Real-world example A production incident is avoided when a code review catches that UseDeveloperExceptionPage was accidentally left unconditional, which would have exposed database connection strings in stack traces to any end user triggering an unhandled exception.

Common follow-ups: What information does UseDeveloperExceptionPage expose that's dangerous in production?;How does the newer IExceptionHandler interface (added in .NET 8) provide more structured error handling?