An error-handling path is a URL path that generates the response shown when an exception or error status code occurs. Middleware can reexecute the request pipeline through this path, allowing the error response to use the application's normal layout and dynamic content. section 4.3.2 section 15.5
Route exceptions to /error
if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/error"); } app.MapGet("/error", () => "Sorry, an error occurred"); When an endpoint throws, ExceptionHandlerMiddleware clears any partial response, changes the request path to /error, reruns the pipeline, and finally returns status code 500. section 4.3.2
Status-code middleware can use a format token such as /{0}. A 404 response then reexecutes the pipeline through /404, while other status codes use their own paths. The handler can tailor the response to the status code. section 15.5
Choose and protect the error-handling path carefully:
- Use a dynamic path when error pages should share menus, layouts, user information, or other generated content. section 4.3.2
- Prefer a static fallback when the dynamic error path might fail, because another error can produce a generic browser error. section 15.5
- Keep production exception responses generic so sensitive application details are not exposed. section 4.3.2
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.
Trace an exception from the original request through pipeline reexecution at /error and into the final JSON response. section 4.3.2
