MVC Exception Filter

Kailash Chandra Behera | Tuesday, June 09, 2020

Introduction

Exception filters apply global policies to unhandled exceptions that occur before the response body has been written to. In this blog we are going to discuss about MVC Exception filter in details and see also how to create custom Exception filter.

Getting Started

Exception filters apply global policies to unhandled exceptions that occur before the response body has been written to, it performs some operation if there is an unhandled exception thrown during the execution of the request in ASP.NET MVC and will redirect the request to the exception page configured in the web configuration file.

For example, let's say there is an action method in your MVC application where you have not used try-catch block inside it to handle the exception and if that function throws an exception while executing request then MVC Exception filter will handle the exception and redirect to the exception page, you configured in the web configuration file.

To implement Exception filter MVC has introduced the HandleError built in the attribute which can be applied over the action method as well as a controller or at the global level for handle the exception in controller and action level. The HandleError filter handles the exceptions which been raised at the controller or actions. Then it returns a custom error view.

Let’s see how the HandleError can be used in the project. Be the below code example shows how to use it.

Over Controller
 namespace mvcfilters.Controllers  
 {  
   [HandleError]  
   public class HomeController : Controller  
   {  
     public ActionResult Index()  
     {  
       return View();  
     }  
   }  
 }  

Exception Filter over Controller

Over Action Method
 namespace mvcfilters.Controllers  
 {  
   public class HomeController : Controller  
   {  
     [HandleError]  
     public ActionResult Index()  
     {  
       return View();  
     }  
   }  
 }  

Exception Filter over Action Method

The HandleError attribute contains a menthod named OnException which invokes whenever and exception occurs and is not handled by code or you can say try catch block. This is inbuild Exception filter you can create your own Exception filter by implementing IExceptionFilter or IAsyncExceptionFilter.

The following sample exception filter uses a custom error view to display details about exceptions that occur when the app is in development:

 public class CustomExceptionFilter : IExceptionFilter  
 {  
   private readonly IWebHostEnvironment _hostingEnvironment;  
   private readonly IModelMetadataProvider _modelMetadataProvider;  
   public CustomExceptionFilter(  
     IWebHostEnvironment hostingEnvironment,  
     IModelMetadataProvider modelMetadataProvider)  
   {  
     _hostingEnvironment = hostingEnvironment;  
     _modelMetadataProvider = modelMetadataProvider;  
   }  
   public void OnException(ExceptionContext context)  
   {  
     if (!_hostingEnvironment.IsDevelopment())  
     {  
       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;  
   }  
 }   

Example of Custom Exception filet in MVC

Note that The HandleError filter works only if the section is turned on in web.config

 <system.web>  
 <customErrors mode="On"></customErrors>  
 </system.web>  
Characteristics of Exception Filter

  1. Can be used to implement common error handling policies.
  2. Don't have before and after events.
  3. Implement OnException or OnExceptionAsync.
  4. Handle unhandled exceptions that occur in Razor Page or controller creation, model binding, action filters, or action methods.
  5. Do not catch exceptions that occur in resource filters, result filters, or MVC result execution.

Related Articles

  1. Various Filters in MVC
  2. MVC Action Filter
  3. MVC Authorization Filters

Thanks