While setting up a default environment for WCF development, I thought it would be a good idea to also include something about fault contracts. A fault contract is an exception class the service can throw to the client containing specific exception information.
The steps to set this up on the service:
- Create a class
- follow naming conventions like ending with 'FaultContract' like 'DefaultFaultContract'
- add one or more properties to the class
- Apply the FaultContract attribute in the interface to the requested method
- Throw the exception in the implementation
- throw new FaultException<DefaultFaultContract>(new DefaultFaultContract("Something went wrong"));
- you can also add a FaultReason to inform the client about the circumstances
After the service is build, the client can be generated using the 'Add service reference', but that won't be something new ;-)
Now the custom exception class is also known on the client and can be caugth with:
- catch (FaultException<SampleService.DefaultFaultContract> ex)
- in ex.Detail you can find your custom fault contract
In Visual Studio it is possible to let the debugger break on unhandled exception. Normally something you want to happen, but in this case it is not a good idea. The debugger thinks that the exception thrown in the service is unhandled, so it breaks saying it found an 'FaultException was unhandled by user code' but in fact the exception is handled by the client.