Fault Contracts In WCF

WCF provides us a facility to specify the fault behavior of our service. It provides a FaultException Class. Whenever our service implementation throws a fault exception, the WCF takes care of serializing that back to the consumer as a SOAP fault. WCF takes care of when our service might issue faults and what type of information will be sent with the fault.

 [ServiceContract]

public interface IMyFirstService  {

[OperationConract]

[FaultContract( typeof MyAppFault)) ]

void MyMethod();

]

WCF FaultException Class comes in two forms:-

  1. FaultException: Used to send untyped data back to the consumer.

  2. FaultException<TDetail> : It is used to send typed fault data back to the consumer. Here TDetail represents the type parameter for the detailed fault information to be serialized back to the consumer as a part of the SOAP fault message. Client catching the exception can access the detailed fault information by getting it from the exception object's Detail property.

FaultContractAttribute property defined in the System.ServiceModel. It enables the service developer to declare which faults a given service might issue. These attributes can be applied to the operations only. It can be applied multiple times, Suppose if our service operation might return different types of faults, we would have a FaultContractAttribute Declaration for each type.
It uses a Type object, used to reference the .NET type of the Details object. This is the type of fault information which we want to bundle with our faults.

A Simple example:

[ServiceContract()]
public interface ICalcService
{
      [OperationContract]
      [FaultContract( typeof(string))]
      double Divide(double numerator, double denominator)
        }
public class CalcService :  ICalcService
{
public double Divide(double numerator, double denominator)
{
            if(denominator ==0.0d)
            {
                  string faultDetail= ”you can not divide it by Zero”l
                  throw new FaultException<string>(faultDetail);
            }
            return numerator/denominator;
      }
}

Ebook Download
View all
Learn
View all