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.
- ExceptionType: Exception Type specifies the type of an exception. If not specified, then HandleError filter handles all the Exception.
- View: Specifies the name of view to display when an exception occurs.
- Master: Master specifies the name of the master view.
- 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).
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
- }
Right click on View and click on Add View.
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>Home</h2>
- @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.
- public ActionResult About()
- {
-
- throw new Exception("Some unknown error encountered!");
- return View();
- }
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.
- <system.web>
- <customErrors mode="On"></customErrors>
- </system.web>
Add HandleError Attribute on About Action method of HomeController.
- [HandleError]
- public ActionResult About()
- {
-
- throw new Exception("Some unknown error encountered!");
- return View();
- }
Add shared folder in Views and then add an Error View (error.cshtml), which will be shown when an exception is thrown.
- @{
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <h3>An error occurred while processing your request. Please contact the administrator.</h3>
Preview
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.
- [HandleError(View = "Error")]
Adding more than One HandleError attribute
We can control the view to be displayed based upon ExceptionType.
-
-
- [HandleError(View = "SpecificError", ExceptionType = typeof(FormatException))]
- [HandleError(Order = 2, View = "Error", ExceptionType = typeof(DivideByZeroException))]
- public ActionResult About()
- {
-
- throw new FormatException();
- return View();
- }
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.
- [HandleError(View = "DetailedError")]
- public ActionResult About()
- {
-
- throw new DivideByZeroException();
- return View();
- }
In the code, shown above, we set DetailedError View for showing the exception.
- @model System.Web.Mvc.HandleErrorInfo
-
- @{
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <h4>Error Details:</h4>
- <p>Controller Name: @Model.ControllerName</p>
- <p>Action Name: @Model.ActionName</p>
- <p>Exception: @Model.Exception</p>
Preview
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:
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- GlobalFilters.Filters.Add(new HandleErrorAttribute());
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- }
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.
- public ActionResult NotFound()
- {
- return View();
- }
NotFound.cshtml Code
- @{
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <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:
- <customErrors mode="On">
- <error statusCode="404" redirect="~/Home/NotFound"/>
- </customErrors>
Preview