Using the Fault Contracts (SOAP Faults) in WCF Programming

In this article, we are going to see, how to use the Fault contracts in WCF programming.

What is WCF?

WCF (Windows Communication Foundation) is a .NET dedicated communication framework. WCF provides an easy way to expose our methods as services and consuming the existing services as traditional methods. (More about the WCF can be found in my previous article: WCF Programming for Beginners.)

What are SOAP Faults?

In all managed applications we use the Exception objects to handle the errors. Similarly in WCF programming also to handle the errors and convey that error information from service to client and client to service we use the SOAP faults. FaultContractAttribute, which is defined in the namespace: System.ServiceModel.FaultContractAttribute, is used to declare customized SOAP faults.
SOAP Faults mainly of two types:
  1. Declared SOAP faults. - These are the SOAP faults that are specified on the operations by using the FaultContractAttribute.
  2. Undeclared SOAP faults. - These are SOAP faults that occurs in the operations but are not specified on the operations by using the FaultContractAttribute.
  1. [AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]  
  2.  public sealed class FaultContractAttribute : Attribute  
Listing 1: Fault Contract Attribute Syntax 

Creating Customized SOAP Faults

To create the customized SOAP faults:
  1. Declare and define the structure for our customized SOAP fault.
  2. Attach the customized SOAP fault to the operations by using the FaultContractAttribute.
  3. Check for the error condition and raise the Customized SOAP fault in service operations.
  4. Handle the SOAP faults at the client side. 
Here I am going to explain all the above steps by using a sample WCF Service.
Sample Program: 
Let us take a WCF service, which has a small function "GetEmpDetails (string EmpID) ". This function accepts empid as input parameter and check for that employee record against the DB. If the employee record exists then it returns that record, if not then it should through a custom fault message to the client, saying that "Employee Record does not exist".
  1. String GetEmpDetails( string EMPID)  
  2. {  
  3.     // Check For the "EMPID" record in DataBase.  
  4.     //On Success return the emp details to the client.  
  5.     //On Failure return the Custom SOAP Fault message to the client.  
  6. }  
STEP 1: Create the Custom Fault Message Definition.
In this sample program we are going to create custom SOAP Fault that contains an error message string property. 
In WCF we have to use the DataContractAttribute, DataMemberAttribute to expose the properties /variable/ events /indexes from WCF service to clients.
  1. /// <summary>  
  2. /// This is structure is used to define the custom soap fault message.  
  3. /// Custom SOAP Fault Message class Name :CustomFaultMsg  
  4. /// </summary>  
  5. [DataContract]  
  6. public struct CustomFaultMsg  
  7. {  
  8.     /// <summary>  
  9.     /// This property is used to pass the custom error information  
  10.     /// from service to client.  
  11.     /// </summary>  
  12.     [DataMember]  
  13.     public string MyCustomErrMsg { getset; }  
  14. }  
Listing 2: Custom Fault Message Structure 
STEP 2: Attach the SOAP fault on the operation
To make use of the fault messages in our SOAP messages we have attach them to the operations by using "FaultContractAttribute". 
  1. /// <summary>  
  2. /// This is class is exposed as services in WCF programming.  
  3. /// </summary>  
  4. [ServiceContract]  
  5. public interface IService  
  6. {  
  7.     /// <summary>  
  8.     /// This method is exposed as the operation in WCF.  
  9.     /// This method searches for an emp : "empid".  
  10.     /// On success it returns the emp details.  
  11.     /// On Failure it raises a Fault Message.  
  12.     /// </summary>  
  13.     /// <param name="EmpId"></param>  
  14.     /// <returns></returns>  
  15.     [OperationContract]  
  16.     [FaultContract(typeof(CustomFaultMsg))]  
  17.     Employee GetEmpDetails(string EmpId);  
  18. }  
"FaultContract[typeof(<<Fault>>)] " attribute is used to add a custom fault to an operation.  In this example, we are adding a custom fault of type "CustomFaultMsg".
"CustomFaultMsg" is structure for our custom fault. (This is defined in step1).
Here function return type "Employee" is an employee structure. "DataContract" attribute is used to expose this structure in service.
  1. /// <summary>  
  2. /// This Data Contract structure for holding the Employee details.  
  3. ///   </summary>  
  4. [DataContract]  
  5. public struct Employee  
  6. {  
  7.     [DataMember]  
  8.     public string FName { getset; }  
  9.     [DataMember]  
  10.     public string LName { getset; }  
  11.     [DataMember]  
  12.     public string DeptID { getset; }  
  13.     [DataMember]  
  14.     public string MailID { getset; }  
  15.     [DataMember]  
  16.     public string Zip { getset; }  
  17. }  
STEP 3: Check for the error condition and raise the customized SOAP fault message: 
In the sample program, IService interface is implemented by a class Service. Here the method GetEmpDetails() should raise our own customized exception, whenever it fails to find the employee details.
  1. /// <summary>  
  2. /// Search the Data Set for an employee of "EmpID".  
  3. /// If the search is successful, then it returns the employee details object to the client.  
  4. /// On an unsuccessful search it throws the customized fault message to the client.  
  5. /// </summary>  
  6. /// <param name="EmpId">Empid</param>  
  7. /// <returns>Employee Object</returns>  
  8. public Employee GetEmpDetails(string EmpId)  
  9. {  
  10.  //Search for the "EmpId" employee details in the data set.  By using the LINQ ..  
  11.  // Add the Dll reference to DataSetExtensions to support for LINQ  
  12.  var empRecord = from dr in ds.Tables[0].AsEnumerable()  
  13.  where dr["EmpId"].ToString() == EmpId  
  14.  select dr;  
  15.  // If their are no records, then we have to raise our customized SOAP Fault Message.  
  16.  if (empRecord.Count() == 0)  
  17.  {  
  18.   //create an object for the custom SOAP Fault.  
  19.   //and initialize the falut with our own customized fault message.  
  20.   CustomFaultMsg custmErr = new CustomFaultMsg {  
  21.    MyCustomErrMsg = "There is no employee exist with the emp id : " + EmpId  
  22.   };  
  23.   //Raise the customized fault message exception to the client.  
  24.   throw new FaultException < CustomFaultMsg > (custmErr);  
  25.  }  
  26.  // if the Emp record is exist , we have to return the emp Details....  
  27.  else  
  28.  {  
  29.   // Create an employee object and store all the emp record details in to the  
  30.   // employee object.  
  31.   Employee objEmp = new Employee();  
  32.   foreach(DataRow dr in empRecord)  
  33.   {  
  34.    // Emp Id is Unique.  
  35.    //So the LINQ select query returns only one row,if the emp exist in the table.  
  36.    objEmp.FName = dr["FirstName"].ToString();  
  37.    objEmp.LName = dr["LastName"].ToString();  
  38.    objEmp.DeptID = dr["DeptId"].ToString();  
  39.    objEmp.MailID = dr["MailId"].ToString();  
  40.    objEmp.Zip = dr["ZipCode"].ToString();  
  41.   }  
  42.   //return the employee object to the client.  
  43.   return objEmp;  
  44.  }  
  45. }  
Listing 3: Sample Program at WCF Service End
In this function, the following LINQ technology is used to search for the emp in the existing data set.  
  1. var empRecord = from dr in ds.Tables[0].AsEnumerable()  
  2.                             where dr["EmpId"].ToString() == EmpId  
  3.                             select dr;   
Error Condition: if (empRecord.Count() == 0) is used to throw the custom falut message. Whenever there is an unsuccessful search for the emp, then this condition become true. And here we are going to initialize the object for our customized fault message and throws the exception to the client.
  1. CustomFaultMsg custmErr =  
  2.          new CustomFaultMsg { MyCustomErrMsg = "There is no employee exist with the emp id : " + EmpId };   
  3.  throw new FaultException<CustomFaultMsg>(custmErr);   
Host this sample Service on IIS under a virtual directory folder Named "WCFService".  Once this service is hosted, next step is to consume the service by the client.
STEP 4: Handling the  SOAP Fault messages in the client program
Here in the client-side while consuming this service use the try and catch blocks to catch the SOAP faults. In Catch blocks, the exception object type should match with our customized SOAP fault created in step1.
Create a client project and add the service reference to our WCFService hosted on IIS:
In the Address: provide the service name, in the namespace "WCFServiceProxy" is used.
In the client program, user will enter for an emp id and click on “GetEmpDetails” button. Inside this button functionality, we are consuming the service and handling the fault messages:
  1. protected void btnSubmit_Click(object sender, EventArgs e)  
  2. {  
  3.  try  
  4.  {  
  5.   //Initialize an proxy object for the Service.  
  6.   WCFServiceProxy.ServiceClient serviceProxy = new ServiceClient();  
  7.   string strEmpId = txtEmpId.Text.Trim();  
  8.   //Consume the WCF Service "GetEmpDetails".  
  9.   WCFServiceProxy.Employee objEmp = serviceProxy.GetEmpDetails(strEmpId);  
  10.   //Add the Employee object to the list, so that it will be displayed on the grid to the user.  
  11.   List < Employee > employeeList = new List < Employee > ();  
  12.   employeeList.Add(objEmp);  
  13.   //Bind the employee list as a datasource to the datagrid.  
  14.   dgEmp.DataSource = employeeList;  
  15.   dgEmp.DataBind();  
  16.  } catch (FaultException < CustomFaultMsg > faultMsg)  
  17.  {  
  18.   //in the faultmsg object , Detail object contains our customized error message information.  
  19.   // property "MyCustomErrMsg" is the one we created in our customized fault message description. in ISecrive.cs file.  
  20.   string errmsg = faultMsg.Detail.MyCustomErrMsg;  
  21.   Response.Write("<Script> alert('" + errmsg + "')</script>");  
  22.  }  
  23. }  
In the client program Exception object should match with our customized Fault type.
Catch(FaultException<<Customized Fault Message >> FaultmessageObject) 
The detail object inside the "FaultmessageObject" contains our customized fault message object. So we used "faultMsg.Detail.MyCustomErrMsg" to get our original customized fault message.
On successful search , the WCF service returns an emp object . This object is added to employee list and displayed to the user in a data grid.
On an unsuccessful search it throws the customized fault message staying that "The emp does not exist".  This SOAP fault is handled and an alert message is displayed.
Using the try catch block at WCF service and throwing the SOAP faults to the client
In the above sample program , emp id is an int type. Now search for an employee id "sa". It throws an exception ,"input string was not in valid format". But in our program, we are not handling these exception.
In other words, at the service side, if there is any unhandled exception is occurred then those exception details are unavailable at the client side. Due to this, at the client side the following generic error message is displayed. This error message doesn't contain any underlying error/exception details.
In the following code snippet, we are using the try catch blocks at the server side and throw original  Exception details to the client. 
To throw the General Exception, first attach the Fault Contract to the service method.
  1. [OperationContract]  
  2. [FaultContract(typeof(CustomFaultMsg))]  
  3. [FaultContract(typeof(Exception))] // newly added for Exception SOAP Fault  
  4. public Employee GetEmpDetails(string EmpId)  
  5. {  
  6.  try  
  7.  {  
  8.   //Search for the "EmpId" employee details in the data set.  By using the LINQ ..  
  9.   // Add the Dll reference to DataSetExtensions to support for LINQ  
  10.   var empRecord = from dr in ds.Tables[0].AsEnumerable()  
  11.   //this part is same as old program. Main changes are  
  12.   // in Exception blocks…  
  13.   //return the employee object to the client.  
  14.   return objEmp;  
  15.  }  
  16. }  
  17. //Catches the Custom Fault message raised in the try block  
  18. catch (FaultException < CustomFaultMsg > custmEx)  
  19. {  
  20.  //Throw the customized SOAP fault to the client program.  
  21.  throw new FaultException < CustomFaultMsg > (custmEx.Detail, "This is from customized Exception block");  
  22. }  
  23. // To catch any other exception.  
  24. catch (Exception ex)  
  25. {  
  26.  //Create the Exception object  and set the exception message .  
  27.  Exception GenEx = new Exception(ex.Message);  
  28.  //throw the Exception SOAP fault  
  29.  throw new FaultException < Exception > (GenEx, "This is from Exception block");  
  30. }  
  31. }  
Listing 3: Server Side Code
In this new code main changes are at exception blocks. Catch(Exception ex) is used to handle the all other exceptions.
At the client Side:
Now we have to handle the General Exception SOAP fault also.
  1. protected void btnSubmit_Click(object sender, EventArgs e)  
  2. {  
  3.  try  
  4.  {  
  5.   //Initialize an proxy object for the Service.  
  6.   WCFServiceProxy.ServiceClient serviceProxy = new ServiceClient();  
  7.   string strEmpId = txtEmpId.Text.Trim();  
  8.   //Consume the WCF Service "GetEmpDetails".  
  9.   WCFServiceProxy.Employee objEmp = serviceProxy.GetEmpDetails(strEmpId);  
  10.   //Add the Employee object to the list, so that it will be displayed on the grid to the user.  
  11.   List < Employee > employeeList = new List < Employee > ();  
  12.   employeeList.Add(objEmp);  
  13.   //Bind the employee list as a datasource to the datagrid.  
  14.   dgEmp.DataSource = employeeList;  
  15.   dgEmp.DataBind();  
  16.  } catch (FaultException < CustomFaultMsg > faultMsg) //This is used to handle the customized SOAP faults raised by WCFService.  
  17.  {  
  18.   //in the faultmsg object , Detail object contains our customized error message information.  
  19.   // property "MyCustomErrMsg" is the one we created in our customized fault message description. in ISecrive.cs file.  
  20.   string errmsg = faultMsg.Detail.MyCustomErrMsg;  
  21.   Response.Write("<Script> alert('" + errmsg + "')</script>");  
  22.  } catch (FaultException < Exception > GenEx) // This handle the general Exception SOAP faults raised by WCFService.  
  23.  {  
  24.   string errmsg = GenEx.Detail.Message;  
  25.   Response.Write("<Script> alert('" + errmsg + "')</script>");  
  26.  } catch (Exception ex) // This is used to handle the exceptions occurred in this client program.  
  27.  // This block does not handles the SOAP faults. This is a Normal catch block.  
  28.  {  
  29.   string errmsg = ex.Message;  
  30.   Response.Write("<Script> alert('" + errmsg + "')</script>");  
  31.  }  
  32. }  
Listing 4: Client Program
In this client program two new exception blocks are added.
catch (FaultException<Exception> GenEx)
Catch the general Exception raised by the WCF Service (not by the client program.)
catch (Exception ex)
This is a standard catch block which is used to catch the exception raised in the client program.
Now it displays the original error message details occurred at WCF Service program. Sample project code is attached.

Similar Articles