Let’s assume that we have a controller in which different types of errors may occur. In this scenario, redirecting the user to a generic error page may not make much sense and may not help user solve the problem if the problem is coming because of data entered by him.
Displaying error specific page and displaying helpful information on that page would make much sense so that the user understand what actually is happening and what action he/she may take to solve the problem.
The other side of this scenario can be showing error page based on error type assigned to team members. Similarly, there can be many other scenario one can think of where we need to show error page specific to that type of error.
Let us see how to achive this functionality.
CONTROLLER CODE
[HandleError(ExceptionType = typeof(NullReferenceException), View = "NullReference")]
public ActionResult HandleError()
{
throw new NullReferenceException("Null reference exception occured.");
}
In the above controller method, we have added a HandleError
attribute where 1st parameter is ExceptionType
(the type of exception we want to catch) and 2nd parameter is the View to show when this type of exception occurs in this action method.
~/VIEWS/SHARED/NULLREFERENCE.CSHTML
@{ ViewBag.Title = "NullReference"; } <h2>Null Reference</h2> Null Reference Error occurred.
Above is the code for the View that renders when NullReferenceException
occurs. As this view has been kept inside the ~/Views/Shared folder so the View name specified in the 2nd parameter of the HandleError
attribute of the action method doesn’t need to specify the path along with this view name.
Similarly, other HandleError
attribute can be applied to the same action method for different types of error.
[HandleError(ExceptionType = typeof(NullReferenceException), View = "NullReference")] [HandleError(ExceptionType = typeof(DivideByZeroException), View = "DivideByZero")] public ActionResult HandleError() { throw new NullReferenceException("Null reference exception occured."); var i = 5; var j = 0; var sum1 = i / j; return View(); }
Notice the above action method where we have two HandleError
attributes for different types of error, both with respective view.
Note that all these will work only when customErrors
mode is “On” in the web.config file.