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,
- Creating First Application In ASP.NET MVC
- Pass Parameter Or Query String In Action Method In ASP.NET MVC
- Passing Data from Controller To View In ASP.NET MVC
- Strongly Typed View Vs Dynamically Typed View In ASP.NET MVC
- Working With Built-In HTML Helper Classes In ASP.NET MVC
- Inline and Custom HTML Helpers In ASP.NET MVC
- CRUD Operation In ASP.NET MVC Using AJAX And Bootstrap
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
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
|
@{
ViewBag.Title = "Index";
}
<h2>Home</h2>
@Html.ActionLink("About Us","About","Home")
|
public ActionResult About()
{
//Throws an exception for demonstration
throw new Exception("Some unknown error encountered!");
return View();
}
|
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.
Add HandleError Attribute on About Action method of HomeController.
<system.web>
<customErrors mode="On"></customErrors>
</system.web>
|
[HandleError]
public ActionResult About()
{
//Throws an exception for demonstration
throw new Exception("Some unknown error encountered!");
return View();
}
|
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<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.
[HandleError(View = "Error")
|
Adding more than One HandleError attribute:
We can control the view to be displayed based upon ExceptionType.
//If Format Exception thrown then SpecificError View is displayed
//If Divide by Zero Exception thrown then Error View is displayed
[HandleError(View = "SpecificError", ExceptionType = typeof(FormatException))]
[HandleError(Order = 2, View = "Error", ExceptionType = typeof(DivideByZeroException))]
public ActionResult About()
{
//Throws an Exception for demonstration
throw new FormatException();
return 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()
{
//Throwing an Exception for demonstration
throw new DivideByZeroException();
return View();
}
|
@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>
|
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:
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.
NotFound.cshtml Code
Now, open web.config file and add the following line of code:
Preview:
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);
}
|
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();
}
|
@{
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>
|
<customErrors mode="On">
<error statusCode="404" redirect="~/Home/NotFound"/>
</customErrors>
|
0 comments:
Post a Comment