Logging Handled Exceptions with ELFAR for ASP.NET MVC
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
{
thrownewNotImplementedException();
}catch(Exceptione)
{
foreach(varfilterinGlobalFilters.Filters)
{
if(filter.InstanceisErrorLogFilter)
{
varf = filter.InstanceasErrorLogFilter;
f.OnException(newExceptionContext(ControllerContext, e));
}
}
}I actually took this one step further and created a .Log() extension method on Exception.
publicstaticclassExceptionExtensions
{
publicstaticvoidLog(thisExceptionexception,ControllerContextcontext)
{
foreach(varfilterinGlobalFilters.Filters)
{
if(filter.InstanceisErrorLogFilter)
{
varf = filter.InstanceasErrorLogFilter;
f.OnException(newExceptionContext(context, exception));
}
}
}
}Then you just need to use it as such:
try
{
thrownewNotImplementedException();
}catch(Exceptione)
{
//...
e.Log(ControllerContext);
}
However, there is an alternative solution: throw the exception and let ELFAR automatically handle it (Figure 1).
Figure 1try
{
thrownewNotImplementedException();
}catch(Exception)
{
//...
throw;
}
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.