Reputation: 4110
Are there any docs on how to correctly implement ExceptionFilterAttribute
? For instance:
context.Result
? Will it serialize that result as the overall response? Does it stop applying any further filters?context.ExceptionHandled
? Does that mean "I'm done processing exceptions, please send the response to the client", or does that mean "I've recovered from the exception, continue processing the request"?base.OnException
or base.OnExceptionAsync
, at the beginning or the end? Do you only call it when your implementation doesn't handle the given exception?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
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?":
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 leavingExceptionHandled==false
. Should remove this special case around settingResul
t.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