Fault Contracts are used to communicate error information from a service to client.They help us to define the errors to be expected from particular service,which we can catch and manage conditions depending on the type of fault.
Introduction
This Article Explains us to how to use Fault Contracts in Windows Communication Foundation
- Fault Contracts are useful when you need report the error to the client.
- It will handle an error by the service class and display in the client side.
- By default when we throw any exception from service, it will not reach the client side. WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract.
Lets look into sample Implementation
Step 1:Create a WCFService Application Here Iam naming it as DemoFaultContractWCF
Step 2 :In the Interface write the following code
Using the code
[ServiceContract]
public interface IFaultContract
{
[OperationContract]
[FaultContract(typeof(OrderItems))]
string OrderGrocery(string ISBN, int Quantity);
}
[DataContract]
public class OrderItems
{
private string info;
public OrderItems(string Message)
{
this.info = Message;
}
[DataMember]
public string msg
{
get { return this.info; }
set { this.info = value; }
}
}
}
Here we are defining Fault Contract for OrderGrocery if the items exceeds 10 it will show the fault Message
The Fault Contract attribute is configured to allow multiple usages so that we can list multiple fault contracts in a single operation as below
public class FaultContractService : IFaultContract
{
#region IFaultContract Members
public string OrderGrocery(string ISBN, int Quantity)
{
int GroceryOnHand = 10;
//check book quantity vs. order quantity
if (Quantity <= GroceryOnHand)
{
return "Order placed";
}
else
{
throw new FaultException(new OrderItems(" You have ordered too many Items"));
}
}
#endregion
}
Create a Client Application and call the WCF Service
Conclusion
We have learned how to Implement Fault Contracts in Windows Communication Foundation.Let me know any issues on Implementation through comments.Thanks for reading my article.