liveBook · Manning

Exception-handler middleware

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

Exception-handling middleware is middleware that catches or processes exceptions raised during request processing.

Exception-handler middleware catches or processes errors raised while a request moves through the ASP.NET Core middleware pipeline. It can modify the response before it reaches the user, returning error details or a generic, friendly HTML page. section 4.3

Its practical role becomes clear in a minimal API pipeline:

  • Place error handling among the middleware components that process requests. section 4.2.3
  • Rely on middleware ordering: an exception can propagate through the pipeline if earlier middleware does not catch it. section 4.2.3 section 4.3
  • Return either diagnostic details or a more user-friendly error response, depending on the configured middleware. section 4.3

A minimal API request pipeline

A realistic minimal API application combines exception handling with static-file, routing, and endpoint middleware. The endpoint produces the normal response; if it throws and no earlier middleware catches the exception, the browser receives a 500 Server Error response. section 4.2.3 section 4.3

Figure 4.10 A simple minimal API application. The application uses only four pieces of middleware: routing middleware to choose the endpoint to run, endpoint middleware to generate the response from a Razor Page, static-file middleware to serve image files, and exception-handler middleware to capture any errors.
CH04_F10_Lock3

Use the pipeline figure to see exception handling alongside routing, endpoint generation, and static-file serving. section 4.2.3

Figure 4.14 An exception in the endpoint middleware propagates through the pipeline. If the exception isn’t caught by middleware earlier in the pipeline, a 500 “Server error” status code is sent to the user’s browser.
CH04_F14_Lock3

Use the propagation figure to trace what happens when endpoint middleware raises an exception that earlier middleware does not catch. section 4.3

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

How deep it goes
Explains pipeline placement, ordering, propagation, and response outcomes without detailing handler implementation.
Examples
Uses a minimal API pipeline and an endpoint exception that produces a 500 Server Error response.
What it assumes
Assumes basic familiarity with WebApplication pipelines and endpoints while distinguishing MapGet endpoint definitions from middleware.
What you can do after
Operate/configure middleware pipelines that provide diagnostic or friendly responses when request processing fails.
How it connects
Connects exception handling with middleware pipelines, routing middleware, endpoint middleware, static-file middleware, and HTTP 500 responses.

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.