Introduction:

In this article, we will explain how to handle an exception using HandleError attribute in ASP.NET MVC with example.

Description:
ASP.NET MVC HandleError attribute provides a built-in exception filter. It can be applied over the action method as well as a controller. However, we can add it at the global level for handling exception in controller and action level. While creating our application, it is automatically included within the Global.asax.cs and registered in FilterConfig.cs, as shown below.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

Now, we need to set the mode to on status for customErrors node of system.web section of web.config file

<customErrors mode="On"></customErrors>

Now, we can use HanldeError attribute at any of the action methods like Index.

[HandleError(View="Error")]
        public ActionResult Index()
        {
            var ID=Request.QueryString["ID"].ToString();
            return View();
        }

Even you can add it at controller level so that it will be applicable to all the action methods present in the controller.

[HandleError(View="Error")]
    public class HomeController : Controller
    {                public ActionResult Index()
        {
            var ID=Request.QueryString["ID"].ToString();
            return View();
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
 
            return View();
        }      }

Note: The HandleError filter works only if the <customErrors> section is turned on in web.config.

<system.web>
    <customErrors mode="On"></customErrors>   
</system.web>

HandleError attribute has some properties as explained below.

ExceptionType:
It specifies the Type of exception to be caught. If it is not specified, then the HandleError filter handles all exceptions.

View:
View name for displaying the exception information.

Master:
Master View for displaying the exception.

Order:
The order in which the action filters are executed. The Order property has an integer value and it specifies the priority from 1 to any positive integer value. Highest priority is 1 and the greater the value of the integer is, the lower is the priority of the filter.

AllowMultiple:
It indicates whether more than one instances of the error filter attribute can be specified.

example.

[HandleError(View ="NullError", ExceptionType =typeof(NullReferenceException))]
        public ActionResult Index()
        {
            var ID=Request.QueryString["ID"].ToString();
            return View();
        }

I hope you will use it after reading.

comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like