Exception Filter In ASP.NET MVC

Introduction

The HandleError attribute is used to display user-friendly error pages to the end users when there is an unhandled exception.

Step 1

Open Visual Studio 2015 or a version of your choice and create a new project.

Step 2

Choose the web application type project and give an appropriate name to your project.
 
Exception Filter in ASP.NET MVC

Step 3

Select the empty template, check on MVC checkbox below, and click OK.
 
Exception Filter in ASP.NET MVC

Step 4

Right-click on the Controllers folder and add a Controller.
 
Exception Filter in ASP.NET MVC

A window will appear. Choose MVC5 Controller-Empty and click "Add".

Exception Filter in ASP.NET MVC

After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of the default, just change Home.

Exception Filter in ASP.NET MVC

The complete code for Home Controller

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.    
  7. namespace ExceptionalFilter_Demo.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         // GET: Home  
  12.         public ActionResult Index()  
  13.         {  
  14.             throw  new Exception("Something went wrong...");  
  15.             //return View();  
  16.         }  
  17.     }  
  18. }  

Step 5

Right-click on the Index method in HomeController. The "Add View" window will appear with default index name checked (use a Layout page); click on "Add.
 
Exception Filter in ASP.NET MVC

Step 6 - Built and run project ctrl+F5

The Index action method throws an exception. As this exception is not handled when we run the application, we will get the default yellow screen of death which does not make sense to the end user.

Exception Filter in ASP.NET MVC

Step 7

Now, we will be replacing this yellow screen of death with a friendly error page.

Enable custom errors in the web.config file that is present in the root directory of MVC application. The “customErrors” element must be nested under “<system.web>“.

  1. <customErrors mode=”On”>  
  2. </customErrors>  

Step 8

Add Shared folder under Views folder if does not exist already. Add Error.cshtml View inside this folder if Error.cshtml does not exist. Write the following HTML in the Error.cshtml view.
 
Exception Filter in ASP.NET MVC
 
Exception Filter in ASP.NET MVC

Run the application and notice that you are redirected to the friendly Error view instead of the generic Yellow screen of death. We have not specified the error page (View) name anywhere, but still, in the response, we get error view whenever an error occurs.

Step 8

Create classFilterConfig if it does not exist under App_Start folder. Write the following code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.    
  7. namespace ExceptionalFilter_Demo.App_Start  
  8. {  
  9.     public class FilterConfig  
  10.     {  
  11.         public static void RegisterGlobalFilters(GlobalFilterCollection filters)  
  12.         {  
  13.             filters.Add(new HandleErrorAttribute());  
  14.         }  
  15.     }  
  16. }  

Step 9

In Global.asax file, in Applicaion_Start() method, RegisterGlobalFilters method is invoked, as shown below. Register FilterConfig in Global.asax file.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7. using ExceptionalFilter_Demo.App_Start;  
  8.    
  9. namespace ExceptionalFilter_Demo  
  10. {  
  11.     public class MvcApplication : System.Web.HttpApplication  
  12.     {  
  13.         protected void Application_Start()  
  14.         {  
  15.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  16.             AreaRegistration.RegisterAllAreas();  
  17.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  18.         }  
  19.     }  
  20. }  
Step 10 - Displaying error detail in the Error view

We will make our error view strongly typed view of model System.Web.Mvc.HandleErrorInfo and then, as usual, using @Model keyword we can access the members. One of the members is the Exception object.

Replace error view with the following code.

  1. @{  
  2.     ViewBag.Title = "Error";  
  3. }  
  4.    
  5. <h2 class="alert-danger">Error Occured</h2>  
  6. <hgroup>  
  7.     <h5 class="text-danger">Controller Name:@Model.ControllerName</h5>  
  8.     <h5 class="text-danger">Action Name:@Model.ActionName</h5>  
  9.     <h5 class="text-danger">Controller Name:@Model.Exception</h5>  
  10. </hgroup>  
Step 11
 
Create different views for different exceptions under the shared folder where we created an error view.
  • cshtml 
  • cshtml 

Step 12

Create a NullReference error view.
 
Exception Filter in ASP.NET MVC
 
Exception Filter in ASP.NET MVC

  1. @{  
  2.     ViewBag.Title = "NullReference";  
  3. }  
  4.    
  5. <h2 class="alert-danger">Error Occured</h2>  
  6. <hgroup>  
  7.     <h5 class="text-danger">Controller Name:@Model.ControllerName</h5>  
  8.     <h5 class="text-danger">Action Name:@Model.ActionName</h5>  
  9.     <h5 class="text-danger">Controller Name:@Model.Exception</h5>  
  10. </hgroup>  

Step 13

Create DividedByZero error view under shared folder.
 
Exception Filter in ASP.NET MVC
 
Exception Filter in ASP.NET MVC

  1. @{  
  2.     ViewBag.Title = "DivideByZero";  
  3. }  
  4.    
  5. <h2 class="alert-danger">Error Occured</h2>  
  6. <hgroup>  
  7.     <h5 class="text-danger">Controller Name:@Model.ControllerName</h5>  
  8.     <h5 class="text-danger">Action Name:@Model.ActionName</h5>  
  9.     <h5 class="text-danger">Controller Name:@Model.Exception</h5>  
  10. </hgroup>  

Complete controller code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.    
  7. namespace ExceptionalFilter_Demo.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         [HandleError(ExceptionType = typeof(NullReferenceException),View = "NullReference")]  
  12.         [HandleError(ExceptionType = typeof(DivideByZeroException),View = "DivideByZero")]  
  13.         [HandleError]  
  14.         public ActionResult Index()  
  15.         {  
  16.             throw  new Exception("Something went wrong...");  
  17.             //return View();  
  18.         }  
  19.    
  20.         public ActionResult TestMethodOne()  
  21.         {  
  22.             throw new NullReferenceException();  
  23.         }  
  24.    
  25.         public ActionResult TestMethodTwo()  
  26.         {  
  27.             throw new DivideByZeroException();  
  28.         }  
  29.     }  
  30. }  

Some of the limitations of the HandleError attribute are -

  1. The error won’t get logged anywhere.
  2. Exceptions raised outside controllers will not be handled. Example- exception raised because of invalid URL won’t be handled.
  3. Exception Handling based on the scenario is not possible. Example – So one error page when the request comes via AJAX and a different one when comes via normal request.

http://localhost:60124/home/TestMethodOne

Exception Filter in ASP.NET MVC

http://localhost:60124/home/TestMethodTwo

Exception Filter in ASP.NET MVC


Similar Articles