Introduction
In a typical Windows application, we use the try..catch..finally block to handle and catch exceptions. But a try..catch block does not work in WCF services. Being a web application, try..catch does not work unless we throw and bubble up the exception.
In WCF, errors can be handled and error message can be conveyed to the client applications using SOAP Fault contract.
Fault Contract provides documented view for error accorded in the service to
client.
Let's see how to use fault contracts in WCF.
Example
1. I created a service with Add operation which will throw general exception as show
below:
- //Service interface
- [ServiceContract()]
- public interface ISimpleCalculator {
- [OperationContract()]
- int Add(int num1, int num2);
- }
- //Service implementation
- public class SimpleCalculator: ISimpleCalculator {
- public int Add(int num1, int num2) { //Do something
- throw new Exception("Error while adding number");
- }
- }
- public int Add(int num1, int num2) {
- //Do something
- throw new FaultException("Error while adding number");
- }
Error while adding number.
3. We can also create your own Custom type and send the error information to the
client using FaultContract.
- Define a type using the data contract and specify the fields you want to return.
- Decorate the service operation with the FaultContract attribute and specify the type name.
- Raise the exception from the service by creating an instance and assigning properties of the custom exception.

Santosh KumarPosted Oct 9, 2013, 7:08 AM
It's helpful.