ExceptionHandlerMiddleware catches exceptions in the ASP.NET Core middleware pipeline and replaces unfriendly or overly revealing responses with a controlled error response. It is intended for production, where exposing stack traces or source details creates a security risk. section 4.3 section 4.3.2
Configure it to provide:
- A JSON or plain-text response for minimal APIs. section 4.3.2
- A custom HTML error page that preserves the application’s look and feel for Razor Pages. section 4.3.2
- A fallback response when an exception would otherwise reach the server and produce a 500 status or an unfriendly page. section 4.3
Use it outside development
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); WebApplication app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/error"); } app.MapGet("/error", () => "Sorry, an error occurred"); section 4.3.2
When an exception is captured, the middleware reexecutes the pipeline using the configured error path, provided response headers have not already been sent. The error endpoint then generates the final response. section 4.3.2 section 4.4
Figure 4.18 ExceptionHandlerMiddleware handling an exception to generate a JSON response. A request to the / path generates an exception, which is handled by the middleware. The pipeline is reexecuted, using the /error path to generate the JSON response.
A request that throws at the root path is handled by ExceptionHandlerMiddleware and reprocessed through /error to produce a JSON response. section 4.3.2

