I'm building an MVC 3.0 ecommerce site. I want to avoid sticking try-catch blocks all over my code.
Question is pretty simple - What is a good strategy for capturing all errors that are thrown on my website? I want to know about all of them... so I can work on bringing that count to 0 once the site goes live. I plan on writing each error to a logger and also to email it.
I've done some reading about capturing it in the global.asax file... but i've also read that it doesn't get ALL of them.
Anyone have any suggestions or can point me in a good direction?
The MVC way of solving that problem are filters. If you are on MVC3 already, global filters are for you. There is special type of filter for handing errors: the HandleError
filter. This article describes much of using it.
You might implement you own filter and control every aspect of of unhandled exceptions, e.g.:
public class HandleExceptionsAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
var expception = filterContext.Exception;
// custom code here..
}
}
Finally, if you want to have all unhandled exceptions to be stored and logged, ELMAH i.e. ELMAH.MVC is the best choice. Install it by using the NuGet package, configure it and all data will be accessed from a link such as:
http://yourapp/admin/elmah/
My suggestion is to not use anything like Application_Error
in Global.asax.cs.
You can handle any thrown Exception in the Global.asax.
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
// global handling code goes here
Server.ClearError();
}