I am using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling for handling exceptions in the application.
I have a handler that logs the exception in our custom logging class. This handler is a part of exception policy definition that has NotifyRethrow as PostHandlingAction.
This is the handler that logs the exception
[ConfigurationElementType(typeof(CustomHandlerData))]
public class ExceptionLoggingHandler : IExceptionHandler
{
public Exception HandleException(Exception exception, Guid handlingInstanceId)
{
Log.Write(exception);
return exception;
}
}
This is my exception policy definition
var throwAndLogPolicy = new ExceptionPolicyDefinition(PolicyType.LogAndThrow, new List<ExceptionPolicyEntry>()
{
new ExceptionPolicyEntry(
typeof(Exception),
PostHandlingAction.NotifyRethrow,
new IExceptionHandler[]
{
new ExceptionLoggingHandler()
})
});
I want to avoid logging the same excpetion twice with this handler. Is this possible with ExceptionHandling application block.
Say we have a MethodA that calls a MethodB that in turn throws an excpetion.
public void MethodA()
{
try
{
MethodB();
}
catch(Exception ex)
{
if(ExceptionPolicy.HandleException(ex, "LogAndRethrow"))
throw;
}
}
public void MethodB()
{
try
{
CallCodeThatThrowsAnException();
}
catch(Exception ex)
{
if(ExceptionPolicy.HandleException(ex, "LogAndRethrow"))
throw;
}
}
This example is legit. MethodB can be called from some other context rather than from MethodA. It just so happens that in this case it is called from MethodA and that method itself has an exception handling block. As you can see this would log my exception twice.
The only solution I came up with is to have a collection of thrown exceptions inside the ExceptionLoggingHandler to keep track of logged exceptions. This way I would log one exception only once. The problem with this solution is that I do not know when to remove the excpetion.