An exception filter handles exceptions raised during MVC or Razor Pages processing. It belongs to the filter pipeline and can inspect the action or page context before returning an appropriate action result. section 22.1.4 section 22.4
Use one when error behavior must be specific to MVC routes or clients. For example, an API can return a JSON-compatible error response instead of the HTML error page produced for Razor Pages by exception-handling middleware. section 22.1.4 section 21.3
Important characteristics:
- Runs after an action method or page handler throws an exception, and runs only once rather than wrapping the response on the way out. section 22.4 section 21.7
- Can access MVC context such as the executing action and its parameters, which supports context-rich logging and route-specific handling. section 22.1.4
- Can short-circuit normal result processing by assigning context.Result; standard result filters do not then run, although always-run result filters can. section 22.2
- Choose synchronous or asynchronous execution according to the services called by the filter, and implement only one interface. section 21.4
Returning ProblemDetails from a filter
A custom HandleExceptionAttribute derives from ExceptionFilterAttribute and overrides OnException. It creates a ProblemDetails object containing a title, exception detail, HTTP 500 status, and type URI, then assigns an ObjectResult containing that object to context.Result. If logging action arguments, avoid recording sensitive values such as passwords or credit-card details. section 22.1.4
