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);
    }
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x