gzak
gzak

Reputation: 4110

How to correctly implement ExceptionFilterAttribute in ASP.NET Core

Are there any docs on how to correctly implement ExceptionFilterAttribute? For instance:

There's no official doc on this and it's not the most obvious thing to implement, so does anyone have either a) good docs - maybe a blog post, or b) a correct sample implementation?

Upvotes: 4

Views: 5281

Answers (1)

Set
Set

Reputation: 49779

Documentation about filters in ASP.NET Core.

Documentation about error handling.

Exception filters handle unhandled exceptions that occur in controller creation, model binding, action filters, or action methods. They won't catch exceptions that occur in Resource filters, Result filters, or MVC Result execution.+

To handle an exception, set the ExceptionContext.ExceptionHandled property to true or write a response. This stops propagation of the exception. Note that an Exception filter can't turn an exception into a "success". Only an Action filter can do that.

Exception filters are good for trapping exceptions that occur within MVC actions, but they're not as flexible as error handling middleware. Prefer middleware for the general case, and use filters only where you need to do error handling differently based on which MVC action was chosen.


Regarding "Does it stop applying any further filters?":

  • Further pipeline execution is stopped if you have unhandled exception, as current method execution is stopped) and exception go up the stack until it is caught in a higher level catch block.

But keep in mind, that final implementation of ExceptionFilterAttribute logic is still in progress. Some changes are expected in next .NET Core MVC 1.1.2.

I have found the following useful explanation is github issue (Exception Filters returns an empty body):

Have confirmed IActionFilters in MVC 5.2.3 and ASP.NET Core 1.1.0 behave the same. However, IExceptionFilters behave differently w.r.t. setting Result but leaving ExceptionHandled==false. Should remove this special case around setting Result.

1.1.0 behaviour is also a regression compared to ASP.NET Core 1.0.x.

Long story about a consistent behaviour for ASP.NET Core:

  • Users can short-circuit most IFilterMetadata implementations by setting Result. But, only on the way in e.g. OnActionExecuting() can short-circuit but OnActionExecuted() cannot.
  • To short-circuit IExceptionFilter implementations (which are only called on the way out), users must set ExceptionHandled==true.
  • Setting ExceptionHandled==true in all IFilterMetadata implementations also ensures an Exception thrown in an action is not rethrown. An overridden Result is used in that case.
  • In a small, intentional deviation from MVC 5.2.3, setting Exception==null is handled identically to setting ExceptionHandled==true.

Upvotes: 1

Related Questions