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:
-
- [ServiceContract()]
- public interface ISimpleCalculator {
- [OperationContract()]
- int Add(int num1, int num2);
- }
-
- public class SimpleCalculator: ISimpleCalculator {
- public int Add(int num1, int num2) {
- throw new Exception("Error while adding number");
- }
- }
2. If we want to send exception information form service to client, we have to use FaultException as shown below
- public int Add(int num1, int num2) {
-
- throw new FaultException("Error while adding number");
- }
Output window on the client side is shown below.
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.
Step 1: Defining the type using
Data Contract
- [DataContract()]
- public class CustomException {
- [DataMember()]
- public string Title;
- [DataMember()]
- public string ExceptionMessage;
- [DataMember()]
- public string InnerException;
- [DataMember()]
- public string StackTrace;
- }
Step 2: Decorate the service operation with the FaultContract
- [ServiceContract()]
- public interface ISimpleCalculator {
- [OperationContract()]
- [FaultContract(typeof(CustomException))]
- int Add(int num1, int num2);
- }
Step 3: Raise the exception from the service
- public int Add(int num1, int num2) {
-
- CustomException ex = new CustomException();
- ex.Title = "Error Funtion:Add()";
- ex.ExceptionMessage = "Error occur while doing add function.";
- ex.InnerException = "Inner exception message from serice";
- ex.StackTrace = "Stack Trace message from service.";
- throw new FaultException(ex, "Reason: Testing the Fault contract");
- }
Step 4: On client side, you can capture the service exception and process
the information, as shown below
- try {
- MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy = new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
- Console.WriteLine("Client is running at " + DateTime.Now.ToString());
- Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5));
- Console.ReadLine();
- } catch (FaultException < MyCalculatorService.CustomException > ex) {
-
- }