Monday, July 22, 2013

What is a Fault Contract in WCF Service?

What is Fault Contract?
Any unexpected error occurred in WCF service can be returned to the client by using Fault Contract.

Process to use Fault Contract in WCF service.

WCF Service:
Step 1: 
Add a data contract in WCF service to return error details to the client; you can also use your existing data contract by adding more properties in it to return error details.

Ex:-
   [DataContract]
    public class MYWCFFaultContract
    {
        [DataMember]
        public bool Result { get; set; }
        [DataMember]
        public string ErrorMessage { get; set; }
        [DataMember]
        public string ErrorDetails { get; set; }
    }

Step 2: 
Add fault contract attribute in the interface Method.

Ex:-
      [ServiceContract]
    public interface IMyWCFService
    {
       [OperationContract]
       [FaultContract(typeof(MYWCFFaultContract))]
       void InsertEmployee(MyWCFDataContract obj);
    }

Step 3: 
Add try catch block in your method, set value to the properties of fault under catch and throw the exception out of the service
Try
{
  \\ Your code
}
catch (Exception ex)
             {
                 objResult.Result = false;
                 objResult.ErrorMessage = "Error Occured in InsertEmployee() method";
                 objResult.ErrorDetails = ex.ToString();
                 throw new FaultException<MYWCFFaultContract>(objResult, ex.ToString());
             }


Client Application:
Step 1: 
Add reference to below namespace on page
      using System.ServiceModel;

Step 2: 
Add try catch block in your code and under catch write the code handle the exception thrown by service
Try
   {
     \\ Your code
   }
catch (FaultException<ServiceReference1.MYWCFFaultContract> excep)
   {
     lblException.Text = excep.Detail.ErrorMessage + " " + excep.Detail.ErrorDetails;
   }


So by this way details of error occurred in service can be returned to the client.


No comments:

Post a Comment