liveBook · Manning

Exception filter

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

An exception filter is an ASP.NET Core MVC filter that handles exceptions raised during action processing and can provide an action result.

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

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

How deep it goes
Explains pipeline timing, context access, short-circuiting, interface choice, and a ProblemDetails implementation, but not registration details.
Examples
Uses a HandleExceptionAttribute that returns ProblemDetails through an ObjectResult with HTTP status 500.
What it assumes
Assumes MVC or Razor Pages request processing and distinguishes filter-specific handling from lower-level middleware.
What you can do after
Apply it via an ExceptionFilterAttribute and return a client-appropriate action result from OnException.
How it connects
Connects exception filters with middleware, MVC filter pipelines, Razor Pages, web API controllers, action results, and result filters.

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.