wcferror-handlingwcfserviceclient

Is it possible to configure a WCF service client to throw a custom FaultException?


I was wondering if it was possible to configure a WCF service client to use a custom type instead of FaultException when throwing faults. The custom type would inherit from FaultException, but also have some additional details about the error.

The reason I want to use a custom FaultException is so I can store a GUID from the SOAP Header which is otherwise lost.

I know I could manually catch and rethrow any faults my service client returns, but that's flimsy. I have no way of guaranteeing future developers will do the same.

I've thought about subclassing the generated service client class and putting the error handling in there, but that generates a lot of work whenever the target service changes.

So, is it possible to configure a WCF service client to throw a custom FaultException type for Faults?


Solution

  • You can create your own IErrorHandler implementation:

    http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx

    Override ProvideFault and then do conversion from regular exceptions (including plain FaultException) to your own custom based FaultException<T>, where T is your own type that you can define to include custom properties.

    After that, you have to register your implementation of IErrorHandler as service behavior, either in code or in web/app config.