Thursday, January 14, 2010

Exception handling in ASP.NET MVC 2

In ASP.NET MVC, handling errors in your controller actions or controller action results can be done using Exception filters. So I applied the HandleError actionfilter on top of my controller. When this exception filter handles an exception, it creates an instance of the HandleErrorInfo class and sets the Model property of the ViewDataDictionary instance when rendering the Error view.

   1:  [HandleError]
   2:  public class HomeController : Controller
   3:  {
   4:      public void Index()
   5:      {
   6:           throw new Exception("Test");
   7:      }
   8:  }


However no exception was catched after applying this filter. After some research I noticed that that this filter doesn’t catch exceptions in debug builds when custom errors are not enabled. The filter simply checks the value of HttpContext.IsCustomErrorEnabled to determine whether to handle the exception.

So open up your web.config and change the CustomErrors mode to On.

   1:  <system.web> 
   2:    <customErrors mode="On"> 
   3:    </customErrors> 

1 comment:

Royce Roy said...

This is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.

http://www.mindstick.com/Articles/3b3db6b5-a464-4ca6-9d77-8b89e824054c/?Exception%20Handling%20in%20ASP%20NET%20MVC3

http://www.codeproject.com/Articles/422572/Exception-Handling-in-ASP-NET-MVC