@Blog.Author(Nandip Makwana) .LearningExperience(ASP.NET, ASP.NET MVC, IIS, jQuery & Technology Surrounding it...)

May 11, 2013 comment

ASP.NET MVC: HandleError action filter

ASP.NET MVC: HandleError

HandleError attribute is used to catch unhandled exception in controller action method. In default MVC template, HandleError attribute is already added to GlobalFilterCollection. In MVC 3, we can see it in Global.asax while in MVC 4 we can see it in App_Start/FilterConfig.cs. One thing to keep in mind is that HandleError will handle exception only if customErrors mode="On" is set in web.config.

Attribute Usage: Controller & method

Sample Code:

[HandleError]
public ActionResult Index()
{
    throw new Exception("HandleError Exception");
    return View();
}

As noted earlier, if we have not set customErrors mode="On" then HandleError will not catch this exception and it will show default YSOD(Yellow Screen Of Death).

YSOD(Yellow Screen Of Death) ASP.NETA

To enable exception catching, enable customErrors in web.config as below.

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

Now again run application, it should catch exception & it should display error.cshtml as displayed below.

With HandleError we can also specify ExceptionType for which to catch unhandled exception, View to display when exception is caught, and Master view.

Check out ASP.NET MVC: Action filter series post to read about other available  action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

comments powered by Disqus

Featured Content

Resources & Tools

About Nandip Makwana

Nandip Makwana is passionate about digital world and web. He completed his Masters in Computer Application in June 2011. Currently he is working as a Software Engineer. He has shown great promise and command over ASP.NET and technologies surrounding it during his academic years and professorial life...continue reading