Project: ExceptionLogging


Instead of have try/finally construct everywhere to catch and log exception, implement an extension method for IDisposable or object class.

Can use as following:
new DisposableObject()
	.UsingWithLog(
		o =>
			{
				o.Method();
				throw new Exception("Test exception.");
			});

Here the extension class:
public static class DisposableExtensions
{
	public static void Using<T>(this T disposable, Action<T> action)
		where T : IDisposable
	{
		try
		{
			action(disposable);
		}
		finally
		{
			if (!EqualityComparer<T>.Default.Equals(default(T)))
			{
				disposable.Dispose();
			}
		}
	}

	public static void UsingWithLog<T>(this T disposable, Action<T> action, bool throwException = false)
		where T : IDisposable
	{
		try
		{
			action(disposable);
		}
		catch (Exception ex)
		{
			DependencyResolver
				.Resolve<ILogger>()
				.Debug(ex);

			if (throwException)
			{
				throw;
			}
		}
		finally
		{
			if (!EqualityComparer<T>.Default.Equals(default(T)))
			{
				disposable.Dispose();
			}
		}
	}
}

Last edited Sep 23, 2011 at 4:04 PM by teoarch, version 1

Comments

No comments yet.