Archive

Archive for the ‘WCF’ Category

Convert WCF Service Exceptions into Faults using Lambdas

December 8th, 2009

Interoperability in WCF is a great thing, but it requires us to rethink our exception handling strategy: The simple paradigm of throwing exceptions whenever something goes wrong doesn’t cut it with distributed systems.

Thankfully, WCF allows us to communicate errors (or faults) through FaultExceptions. We can just convert internal exceptions into a FaultException, and WCF will take care about everything else. However: This conversion strategy is tedious and error prone, especially if you want to do more sophisticated exception handling. Even a simplified example as the one below mainly consists of exception handling code:

//Simplified example
public string Foo(string userName)
{
  try
  {
     Bar.FooBar(userName);
  }
  catch(ArgumentException e)
  {
    //convert exception into a WCF friendly FaultException
    throw new FaultException("Info about specific error");
  }
  catch(Exception e)
  {
    //convert exception into a WCF friendly FaultException
    throw new FaultException("Info about unspecific error");
  }
}

 

I’m currently finding myself having to write a set of WCF services, and I didn’t want to go through try/catch blocks all the time just in order to wrap up the same exceptions over and over again. Accordingly, I wrote helper methods that do the exception handling for me.

  • SecureAction is used by service methods that do not have a return value.
  • SecureFunc<T> is used by service methods that do have a return value.

These helper methods allow me to easily delegate the exception handling from all my service methods, and if anything goes wrong, I can trust that the internal exception is safely converted into a FaultException. Here’s is the rewritten Foo method from above, now remarkably smaller:

public string Foo(string userName)
{
  return SecureFunc(() => Bar.FooBar(userName));
}

 

Below is the (simplified) snippet with the helper methods. Do note that the above sample methods are just starting points. My productive helper methods provide a more sophisticated exception handling than shown above (they build detailed FaultContracts which are specific to my application) and come with a few overloads.

Furthermore, you might think about adding additional parameters to your helper methods (such as fault IDs) in order to customize the generated faults.

public static void SecureAction(Action action)
{
  try
  {
    action();
  }
  catch (Exception e)
  {
    //productive code provides more specific
    //exception handling, but you should get the idea...
    throw new FaultException(e.Message);
  }
}

public static T SecureFunc<T>(Func<T> func)
{
  try
  {
    return func();
  }
  catch (Exception e)
  {
    //productive code provides more specific
    //exception handling, but you should get the idea...
    throw new FaultException(e.Message);
  }
}
Author: Categories: C#, WCF Tags: