ASP.Net MVC Exception Logging combined with Error Handling
Posted
by Saajid Ismail
on Stack Overflow
See other posts from Stack Overflow
or by Saajid Ismail
Published on 2009-06-23T12:50:45Z
Indexed on
2010/05/09
20:38 UTC
Read the original article
Hit count: 551
Hi. I am looking for a simple solution to do Exception Logging combined with Error Handling in my ASP.Net MVC 1.0 application.
I've read lots of articles, including Questions posted here on StackOverflow, which all provide varying solutions for different situations. I am still unable to come up with a solution that suits my needs.
Here are my requirements:
To be able to use the [HandleError] attribute (or something equivalent) on my Controller, to handle all exceptions that could be thrown from any of the Actions or Views. This should handle all exceptions that were not handled specifically on any of the Actions (as described in point 2). I would like to be able to specify which View a user must be redirected to in error cases, for all actions in the Controller.
I want to be able to specify the [HandleError] attribute (or something equivalent) at the top of specific Actions to catch specific exceptions and redirect users to a View appropriate to the exception. All other exceptions must still be handled by the [HandleError] attribute on the Controller.
In both cases above, I want the exceptions to be logged using log4net (or any other logging library).
How do I go about achieving the above? I've read about making all my Controllers inherit from a base controller which overrides the OnException method, and wherein I do my logging. However this will mess around with redirecting users to the appropriate Views, or make it messy.
I've read about writing my own Filter Action which implements IExceptionFilter to handle this, but this will conflict with the [HandleError] attribute.
So far, my thoughts are that the best solution is to write my own attribute that inherits from HandleErrorAttribute. That way I get all the functionality of [HandleError], and can add my own log4net logging. The solution is as follows:
public class HandleErrorsAttribute: HandleErrorAttribute {
private log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception != null)
{
log.Error("Error in Controller", filterContext.Exception);
}
base.OnException(filterContext);
}
}
Will the above code work for my requirements? If not, what solution does fulfill my requirements?
© Stack Overflow or respective owner