In the previous chapter, we saw how to redirect to specific actions when an error occurs. Another option could be to leverage the IExceptionFilter and IAsyncExceptionFilter interfaces, one of the filter classes, to have the controller itself—or some other class—implement error handling directly.
In our controller, it's just a matter of implementing theIExceptionFilterclass, which only has one method,OnException:
public void OnException(ExceptionContext context)
{
var ex = context.Exception;
//do something with the exception
//mark it as handled, so that it does not propagate
context.ExceptionHandled = true;
}
In the asynchronous version, IAsyncExceptionFilter, the OnExceptionAsync method takes the same parameter but must return a Task.
In Chapter 10, Understanding Filters, we will learn more about the concept of filters. For now, it is enough to say that should any exception be thrown from an action in...