liveBook · Manning

ExceptionHandlerMiddleware

As explained in ASP.NET Core in Action, 3e

Error-handling middleware is middleware that intercepts application errors and modifies the HTTP response before it is returned to the client.

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.
CH04_F18_Lock3

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains response replacement, environment-based registration, and pipeline reexecution, but defers building custom middleware.
Examples
Uses /error endpoints, generic JSON or plain-text responses, and branded Razor Pages error pages as concrete handlers.
What it assumes
Assumes familiarity with ASP.NET Core middleware pipelines and exceptions while contrasting development and production error handling.
What you can do after
Configure it via UseExceptionHandler to deliver safe production error responses without exposing sensitive application details.
How it connects
Connects middleware pipelines with DeveloperExceptionPageMiddleware, hosting environments, custom error endpoints, and Problem Details.

Also explained in

Compare how 2 books explain ExceptionHandlerMiddleware →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.