How to use Exception filters in ASP.NET Core MVC?
In ASP.NET Core MVC we have the option to filter Exceptions in MVC execution pipeline, and it's handy too, for developer as we know when it comes no one like, so having an option to handle it seems interesting, in ASP.NET framework also we have the option to handle it, but as we are focusing on ASP.NET Core MVC in this post, let's see some important note on Exception filter.
What is Exception filter?
A custom class where we can write our logic to execute on action method execute in ASP.NET Core MVC. It is used to apply global policies to unhandled exceptions which can occur before anything has been written to the response body.
Exception filter implements either IExceptionFilter or IAsyncExceptionFilter interface, not both. We can use to implement common error handling policies for an application.
Note:- Unlike other filter Exception filter doesn't have before and after events.
A simple custom class from docs.microsoft.com looks like,
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IModelMetadataProvider _modelMetadataProvider;
public CustomExceptionFilterAttribute(
IHostingEnvironment hostingEnvironment,
IModelMetadataProvider modelMetadataProvider)
{
_hostingEnvironment = hostingEnvironment;
_modelMetadataProvider = modelMetadataProvider;
}
public override void OnException(ExceptionContext context)
{
if (!_hostingEnvironment.IsDevelopment())
{
// do nothing
return;
}
var result = new ViewResult {ViewName = "CustomError"};
result.ViewData = new ViewDataDictionary(_modelMetadataProvider,context.ModelState);
result.ViewData.Add("Exception", context.Exception);
// TODO: Pass additional detailed data via ViewData
context.Result = result;
}
}
Exception filter
- Exception filter implement OnException or OnExceptionAsync
- Handle unhandled exceptions that can occur in controller actions, model binding, action filters, or action methods.
- Exception filter can't turn an exception into a "success". Only an Action filter can do that. To know more about Action filter check Action filter
- We do not catch exceptions that can occur in Resource filters, Result filters, or MVC Result execution.
Note:- Exception filter is good for Trapping exceptions that occur within MVC actions & are not as flexible as error handling in middleware.
Prefer middleware for exception handling. Use exception filters only where we need to do error handling differently based on which MVC action was chosen.