0 Comments

Erik Funkenbusch posted a question, on the ELFAR discussion board, regarding the logging of handled exceptions. He managed to figure out a solution and kindly posted it:

FYI, I found a solution that works pretty well.

try
{
    throw new NotImplementedException();
}
catch (Exception e)
{
    foreach (var filter in GlobalFilters.Filters)
    {
        if (filter.Instance is ErrorLogFilter)
        {
            var f = filter.Instance as ErrorLogFilter;
            f.OnException(new ExceptionContext(ControllerContext, e));
        }
    }
}

I actually took this one step further and created a .Log() extension method on Exception.

public static class ExceptionExtensions
{
    public static void Log(this Exception exception, ControllerContext context)
    {
        foreach (var filter in GlobalFilters.Filters)
        {
            if (filter.Instance is ErrorLogFilter)
            {
                var f = filter.Instance as ErrorLogFilter;
                f.OnException(new ExceptionContext(context, exception));
            }
        }
    }
}

Then you just need to use it as such:

try
{
    throw new NotImplementedException();
}
catch (Exception e)
{
    //...
    e.Log(ControllerContext);
}

However, there is an alternative solution: throw the exception and let ELFAR automatically handle it (Figure 1).

try
{
    throw new NotImplementedException();
}
catch (Exception)
{
    //...
    throw;
}
Figure 1

Update:

Erik responded with some good points:

Rethrowing the exception will result in an unhandle exception propogating to the client...The whole point is to handle th[e] exception, but log it so it can be investigated. I find this particularly useful with exceptions for external resources (Web requests, file access, etc..). There is no point in passing this on to the user if you can continue.

Comments