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.
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.
Use the propagation figure to trace what happens when endpoint middleware raises an exception that earlier middleware does not catch. section 4.3
