首页 > 解决方案 > Log all handles exception

问题描述

How can I log all handled exceptions?

I want that whenever I catch an exception I should be able to log it

I want it to work globally and not that i should have to write it each time I catch

I tried subscribing to AppDomain.CurrentDomain.FirstChanceException and it did work but I did not have the full stack trace and it called multiple times for each exception (I don't know why)

I also tried wrapping my controller with ActionFilterAttribute like below and it worked on all exception from the controller only and not if the exception was caught in a service that was called from the controller

 public class ExceptionLoggingHandler : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        if(filterContext.Exception !=null)
        {
            System.Diagnostics.Debug.WriteLine(filterContext.Exception.Message);
        }
        base.OnResultExecuted(filterContext);
    }
}

标签: c#asp.netasp.net-mvcexceptionlogging

解决方案


In ASP.NET MVC, you can add your filter as a global filter in the RegisterGlobalFilters method inside FilterConfig.cs. It should then catch all exceptions in all controller actions, and in any methods called from those actions - unless of course those methods already have catch blocks inside them which swallow the exception. In that case the caught exception (unless it's then re-thrown) will inevitably go undetected higher up the stack, which is, naturally, the whole point of catching exceptions.

e.g.

public class FilterConfig
{ 
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) { 
       filters.Add(new ExceptionLoggingHandler()); 
    } 
}

Also, your attribute should inherit from HandleErrorAttribute, not ActionFilterAttribute.

Something like this:

public class ExceptionLoggingHandler : HandleErrorAttribute 
{

    public ExceptionLoggingHandler() : base()
    {
    }

    public override void OnException(ExceptionContext context)
    {
        System.Diagnostics.Debug.WriteLine(context.Exception.Message);
        context.ExceptionHandled = true;
        //.... continue to produce a suitable response
    }
}

(In the .... area you can continue to develop the handler to log more sophisticated data, and return a suitable response, perhaps along the lines of this one (other examples are also available online.)


推荐阅读