How to Shield Exception Information with Fault Contracts

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

A fault contract details the set of exceptions that may be reported to the caller. You can specify the possible faults that can occur in you WCF service. This prevents exposing exception details beyond the defined set to your clients. Since a fault contract lists the type of errors that a WCF service can throw it also allows your clients to distinguish between contracted faults and other possible errors.

Use the following steps to shield exception information with fault contracts.
  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());
   }
}

Additional Resources

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

Comments

No comments yet.