Fault Contracts in WCF services

Aug 17, 2011 at 10:42 AM


Recently I was asked to raise a custom exception in the WCF Services which will be handled on the client side. As a normal programmer I created a custom exception in my service and left on the client side to handle. Assuming that it will be sent on the client side as it is. Instead it showed me this error.

Fault Contracts in WCF services

 

Little as I knew, something clicked me that if we pass/return the custom objects it has to be defined as a contract. As contracts are the only thing that WCF uses to communicate with the client.

I googled a bit around and came with the concept of Fault Contracts. Consider I have created a custom exception class as defined below

 

 [DataContract()]  
   public class CustomException  
   {  
     [DataMember()]  
     public string Title;  
     [DataMember()]  
     public string ErrorMessage;  
     [DataMember()]  
     public int ErrorCode;  
     [DataMember()]  
     public string StackTrace;      
   }  

Now if I throw this exception directly to the client, it would not recognize it. Hence any method which can raise this exception should specify the attribute while defining it. (as shown below)

 

 [ServiceContract()]  
   public interface IService  
   {  
     [OperationContract()]  
     [FaultContract(typeof(CustomException))]  
     String MyMethod(string inputParams);  
   }    

 

 The next step is throwing the exception from the method

 

 public String MyMethod (string inputParams)  
     {  
     CustomException error = new CustomException();  
     error.Title = "my custom exception for fault contracts";  
     error.ErrorMessage = "Error in MyMethod";  
     error.ErrorCode = 1001;  
     error.StackTrace = "custom stack trace";  
     throw new FaultException(error,"Reason: Testing the Fault contract");  
     }  

 

 While on the client side , you can catch the thrown exception as shown below,

 

  try  
     {  
     Proxy.MyMethod(“Kalashnikov”);  
     }  
     catch (FaultException ex)  
     {  
     //Process the Exception as thrown  
     }  

Found this article by Dhaval Shah valuable? Help by Sharing ...

  • Click on the banners at the top of article or in the right panel to visit my blog's sponsors. They are all hand-picked and are selected based on providing great products and services to the SharePoint community.
  • I’d be very grateful if you’d help it spread by Sharing. Below, you should find links to sharing this article on your favorite social media sites.
Related Posts by Dhaval Shah blog comments powered by Disqus