Reusable Generic Exception Wrapper in C#

When crossing boundaries between software layers you are sometimes faced with the requirement to wrap a meaningless exception from a lower layer into a more meaningful exception for users from the higher layer. The pattern described below helps with implementing this requirement in a reusable way. It is in no way meant to be a catch-all for every situation where you have to deal with exceptions, but when applied correctly can prove to be an invaluable tool in your toolkit. See Framework Design Guidelines, Chapter 7 (7.2.3) for more one exception wrapping.

The approach used is to wrap the logic that can fail in a delegate and have this delegate executed by the WrapExceptions method. The WrapExceptions method then takes responsibility of handling the exceptions appropriately. It should be modified to handle only the applicable exceptions; some exceptions you might not want to wrap e.g. StackOverflowException, OutOfMemoryException and ThreadAbortException because you cannot recover from them. An added advantage of wrapping the failure prone code in a delegate is that it allows you to easily wrap it around existing code.

The WrapExceptions code snippet:

// public delegate void Action();

public static void WrapExceptions(Action action)

{

   try

   {

      action();

   }

   catch (MyApplicationException)

   {

      // just rethrow exception, it

      // was already properly handled

      throw;

   }

   catch (Exception e)

   {

      throw new MyApplicationException(e);

   }

}

And then you can use it as follows:

public void WrapMyException(string filepath, string myLine)

{

   WrapExceptions(delegate()

   {

      using (TextWriter writer = new StreamWriter(filepath))

      {

         writer.WriteLine(myLine);

      }

   });

}

Let me know your thoughts on this approach. What problems did it solve, and did it introduce new ones?


No comments:

Post a Comment

My Latest Track