title: ASP.Net MVC Exception Logging combined with Error Handling
body: <p>I am looking for a simple solution to do Exception Logging combined with Error Handling in my ASP.Net MVC 1.0 application.</p>
  
  <p>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.</p>
  
  <p>Here are my requirements:</p>
  
  <ol>
  <li><p>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.</p></li>
  <li><p>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.</p></li>
  <li><p>In both cases above, I want the exceptions to be logged using log4net (or any other logging library).</p></li>
  </ol>
  
  <p>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.</p>
  
  <p>I've read about writing my own Filter Action which implements IExceptionFilter to handle this, but this will conflict with the [HandleError] attribute.</p>
  
  <p>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:</p>
  
  <pre><code>    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);
        }
     }
  </code></pre>
  
  <p>Will the above code work for my requirements? If not, what solution does fulfill my requirements?</p>