ASP.NET MVC: HandleError action filter
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).
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.