Exception Filter In MVC

Exception filter in MVC provides an ability to handle the exceptions for all the controller methods at a single location. This is by creating a class, which inherits from the FilterAttribute and IExceptionFilter interface.

Here, the FilterAttribute class makes it possible to use the class as an attribute and IExceptionFilter interface contains the method named OnException. OnException is executed whenever any exception occurs in the controller action method. In case try-catch block is applied in the action method and an exception occurs within the try block code, this filter will not be executed. This kind of technique is quite helpful for logging purposes. Thus, let's see how we can use this filter.

Let's start by adding a new class named MyExceptionFilter.cs. Now, derive this class from the FilterAttribute and the IExceptionFilter. Implement the OnException method and add your custom logic into the method. Hence, the code will look, as shown below. 
  1. public class MyExceptionFilter: FilterAttribute, IExceptionFilter  
  3.   {  
  4.     public void OnException(ExceptionContext filterContext) {  
  5.         //Handle exception here  
  6.     }  
  7. }  
Apply the class name as an attribute on the controller class. Add an exception in the controller Index method. We will generate an attempt to divide by zero exception. Do not add any try-catch block.
  1. [MyExceptionFilter]  
  2. public class HomeController: Controller {  
  3.     public ActionResult Index() {  
  4.         int a = 10;  
  5.         int b = 0;  
  6.         int c = a / b;  
  7.         return View();  
  8.     }  
  9.     public ActionResult About() {  
  10.         ViewBag.Message = "Your application description page.";  
  11.         return View();  
  12.     }  
  13.     public ActionResult Contact() {  
  14.         ViewBag.Message = "Your contact page.";  
  15.         return View();  
  16.     }  
  17. }  
Run the Application and see the results. The OnException method gets executed.

Now, if you add the try-catch block on the code, the OnException method will not be executed at all. Hope, you enjoyed reading it. Happy coding.