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.
- public class MyExceptionFilter: FilterAttribute, IExceptionFilter
-
- {
- public void OnException(ExceptionContext filterContext) {
-
- }
- }
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.
- [MyExceptionFilter]
- public class HomeController: Controller {
- public ActionResult Index() {
- int a = 10;
- int b = 0;
- int c = a / b;
- return View();
- }
- public ActionResult About() {
- ViewBag.Message = "Your application description page.";
- return View();
- }
- public ActionResult Contact() {
- ViewBag.Message = "Your contact page.";
- return View();
- }
- }
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.