Convert WCF Service Exceptions into Faults using Lambdas

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:

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:

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.

There is no helpers class – my implementation is basically the same snippet as above, with the difference that it handles exceptions (and creates faults) that are specific to my application.

However, I find myself applying this pattern in more and more situations (not only WCF, but everywhere I just want to make sure proper exception handling is made). For example in order to log an exception before rethrowing it again: