A few weeks ago I posted a preliminary version of a WCF error handling behavior which facilitated automatic translation of server-side exceptions to faults.
Since then, I have reconsidered parts of my approach. It occurred to me that the most proper way of mapping exceptions to faults is using attributes – the same way that is used to declare fault contracts in the first place.
Therefore, I reworked the solution to use an attribute on the operation level – a [MapExceptionToFault] attribute. The attribute can be used to map an exception type to a fault detail type on a specific operation. This is a significantly more intuitive and useful approach than having a catch-all event handler that would be responsible for detecting the current operation and translating the fault accordingly.
Additionally, the attribute-based approach allows for validation. As part of the IServiceBehavior implementation, I can now use the Validate method to make sure that the operation on which the attribute has been placed indeed exposes an appropriate fault contract.
(I’ve also used the opportunity to rework the code that detects the current operation. There’s in fact a clean way of doing it using the WCF operation context API: Find the current endpoint, ask it for the dispatch operations and find the one matching the current action, extract the operation description from the contract on the endpoint.)