Skip to content

Instantly share code, notes, and snippets.

@Warrenn
Created July 1, 2015 14:50
Show Gist options
  • Save Warrenn/33438ffa48298d587d94 to your computer and use it in GitHub Desktop.
Save Warrenn/33438ffa48298d587d94 to your computer and use it in GitHub Desktop.
A useful Method to wrap the Enterprise Library ExceptionHandler safely calls finalize and ensures that logging will happen
using System;
using LoadFileData.Constants;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
public static class ExceptionHandler
{
public static void Dispose(this IDisposable disposable, string policyName = PolicyName.Disposable)
{
if (disposable == null)
{
return;
}
Try(disposable.Dispose, policyName, () => { disposable = null; });
}
public static void Try(
Action tryAction,
string policyName = PolicyName.Default,
Action finallyAction = null)
{
try
{
tryAction();
}
catch (Exception exception)
{
Exception rethrowException;
policyName = string.IsNullOrEmpty(policyName) ? PolicyName.Default : policyName;
if (ExceptionPolicy.HandleException(exception, policyName, out rethrowException))
{
if (rethrowException == null)
{
throw;
}
throw rethrowException;
}
}
finally
{
if (finallyAction != null)
{
Try(finallyAction, policyName);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment