How to Avoid Faulting the Channels with Fault Contracts

- J.D. Meier, Carlos Farre, Jason Taylor, Prashant Bansode, Steve Gregersen, Madhu Sundararajan, Rob Boucher

When calling a WCF service, if there are any exceptions thrown by the service, the communication channel goes into the faulted state, and you cannot use the proxy for any further calls. This can be avoided by throwing FaultException in your service operations. The service operation that throws a FaultException must be decorated with one or more FaultContract attributes.
  1. Define a Fault contract by applying the FaultContract attribute directly on a contract operation, and specifying the error detailing type to the method as shown below:
[ServiceContract]
interface ICalculator
{
   [OperationContract]
   [FaultContract(typeof(DivideByZeroException))]
   double Divide(double number1,double number2);
}
  1. Implement the Divide operation which throw the fault and have it propagated to the client by throwing exactly the same detailing type listed in the fault contract.
class MyService : ICalculator
{
   public double Divide(double number1,double number2)
   {
      throw new FaultException<DivideByZeroException>(new DivideByZeroException());
   }
}
  1. Handle the faults at the client by catching the FaultException and also other communication exceptions that could occur when calling the service operations.
try
{
  proxy.Divide();
}
catch (FaultException<DivideByZeroException> ex)
{
  // only if a fault contract of type DivideByZeroException was specified 
}

catch (FaultException ex)
{
  // any other faults 
}

catch (CommunicationException ex)
{
  // any communication errors? 
}

Additional Resources

Last edited Jun 13, 2008 at 6:41 PM by prashantbansode, version 1

Comments

No comments yet.