HandleError Action Filter In ASP.NET MVC

In this article, you will learn how to handle errors using HandleError Action Filter in ASP.Net MVC. In previous ASP.NET MVC tutorials of this series, we saw,
In all the software Applications, Exception Handling plays a critical role. An exception can also be thrown during runtime, because of some mathematical calculations, some invalid data, or maybe because of network failure etc. ASP.NET MVC has HandleError Attribute (Action Filter), which provides one of the simplest ways to handle errors. HandleError Attribute has a couple of properties which are useful in handling an exception and help in modifying the default behavior of HandleError Attribute.
  1. ExceptionType: Exception Type specifies the type of an exception. If not specified, then HandleError filter handles all the Exception.

  2. View: Specifies the name of view to display when an exception occurs.

  3. Master: Master specifies the name of the master view.

  4. Order: If more than one HandleError attribute is used, then the order specifies the order of the filters applied. We can set an integer from -1 (Highest Priority) to any positive integer. If no order is specified, then the Order value is -1.
In order to use HandleError Attribute, first, we have to enable Custom Error in web.config file.

Let’s Start,

Create a new ASP.NET MVC Project.

Select Empty MVC Template and click OK.

Now, right click on the Controller and add Empty Controller (name it as HomeController).

  1. public class HomeController : Controller  
  2. {  
  3.         // GET: Home  
  4.         public ActionResult Index()  
  5.         {  
  6.             return View();  
  7.         }  
  8. }  
Right click on View and click on Add View.
  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  5. <h2>Home</h2>  
  6. @Html.ActionLink("About Us","About","Home")  
I have also added About Action method in HomeController. For demonstration purposes, I will throw an exception on calling About Action Method.
  1. public ActionResult About()  
  2. {  
  3.             //Throws an exception for demonstration  
  4.             throw new Exception("Some unknown error encountered!");  
  5.             return View();  
  6.  }  
On clicking About us link, you will see the exception is thrown and Yellow Screen of death appears.

Hackers can easily take advantage of the yellow screen of death, because it shows some valuable/secret code. In order to prevent the Yellow screen of death, we have to add Custom Error in web.config file.
  1. <system.web>  
  2.     <customErrors mode="On"></customErrors>  
  3. </system.web>  
Add HandleError Attribute on About Action method of HomeController.
  1. [HandleError]  
  2. public ActionResult About()  
  3. {  
  4.             //Throws an exception for demonstration  
  5.             throw new Exception("Some unknown error encountered!");  
  6.             return View();  
  7. }  
Add shared folder in Views and then add an Error View (error.cshtml), which will be shown when an exception is thrown.

  1. @{  
  2.     Layout = "~/Views/Shared/_Layout.cshtml";  
  3. }  
  5. <h3>An error occurred while processing your request. Please contact the administrator.</h3>  


We can also declare HandleError attribute on the Controller level as well as on Action method. Declare HandleError attribute on an Action method. 


Declare HandleError attribute on the Controller level.


Using View property of HandleError attribute, we can show the specified view on getting unhandled exceptions.
  1. [HandleError(View = "Error")]  
Adding more than One HandleError attribute

We can control the view to be displayed based upon ExceptionType.
  1. //If Format Exception thrown then SpecificError View is displayed  
  2. //If Divide by Zero Exception thrown then Error View is displayed  
  3. [HandleError(View = "SpecificError", ExceptionType = typeof(FormatException))]  
  4. [HandleError(Order = 2, View = "Error", ExceptionType = typeof(DivideByZeroException))]  
  5. public ActionResult About()  
  6. {  
  7.        //Throws an Exception for demonstration  
  8.        throw new FormatException();  
  9.        return View();  
  10. }  
In the example shown above, if FormatException Occurs, then it will Show SpecificError.cshtml error view or if DivideByZeroException Exception occurs, then it will show Error.cshtml View.
Show Error Details

We can also show error detail on getting an exception. HandleErrorInfo class provides information for handling an error that is thrown by the Action method. HandleErrorInfo has several properties like ActionName, ControllerName, and Exception, which help in getting additional information about the exception.
  1. [HandleError(View = "DetailedError")]  
  2. public ActionResult About()  
  3. {  
  4.        //Throwing an Exception for demonstration  
  5.        throw new DivideByZeroException();  
  6.        return View();  
  7. }  
In the code, shown above, we set DetailedError View for showing the exception.
  1. @model System.Web.Mvc.HandleErrorInfo  
  3. @{  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  7. <h4>Error Details:</h4>  
  8. <p>Controller Name: @Model.ControllerName</p>  
  9. <p>Action Name: @Model.ActionName</p>  
  10. <p>Exception: @Model.Exception</p>  

Setting HandleError Attribute as a Global Filter

We can register HandleError attribute as a global error handling filter. Open Global.asax file and add the code, given below:
  1. protected void Application_Start()  
  2. {  
  3.        AreaRegistration.RegisterAllAreas();  
  4.        GlobalFilters.Filters.Add(new HandleErrorAttribute());  
  5.        RouteConfig.RegisterRoutes(RouteTable.Routes);  
  6. }  
Now, remove all the HandleError attributes from HomeController, build and run the Application.
Handle Errors related to Http Status Code

If we visit the path that doesn’t exist it will throw an HTTP 404 exception.


In order to handle it, first, we have to add an Action Method (NotFound in my case), which will return the NotFound.cshtml view.
  1. public ActionResult NotFound()  
  2. {  
  3.        return View();  
  4. }  
NotFound.cshtml Code
  1. @{  
  2.     Layout = "~/Views/Shared/_Layout.cshtml";  
  3. }  
  5. <h4>HTTP 404. The resource you are looking for doesn’t exist or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.</h4>  
Now, open web.config file and add the following line of code:
  1. <customErrors mode="On">  
  2.       <error statusCode="404" redirect="~/Home/NotFound"/>  
  3. </customErrors>  

Up Next
    Ebook Download
    View all
    View all