in WCF

WCF – Handling Errors – Part 1

Earlier in my post, I discussed  how you can structure WCF projects. Few things are still missing in that structure, especially Error Handling. With the current architecture, which is shown below, we can handle Errors and send meaningful information back to the Client. This is done using FaultExceptions.

Using FaultContracts is pretty easy. We specify what FaultContract each OperationContract is associated with. We don’t specify any fault if the OperationContract does not have any FaultContract.

   1: [ServiceContract]
   2: public interface IMyService
   3: {
   4:     [OperationContract]
   5:     [FaultContract(typeof(MyServiceFault))]
   6:     string GetData(Nullable<int> value);
   7: 
   8:     [OperationContract]
   9:     CompositeType GetDataUsingDataContract(CompositeType composite);
  10: }

 

And throw it when we want to:

   1: throw new FaultException<MyServiceFault>(
   2:     new MyServiceFault()
   3:     {
   4:         FaultName="ArgumentFault",
   5:         FaultMessage="Please supply a valid value"
   6:     });

 

The Client can catch this FaultException and get the ‘friendly’ exception messages:

   1: try
   2: {
   3:     string strValue = proxy.GetData(nValue);
   4: 
   5:     Console.WriteLine("You supplied : {0}", nValue.ToString());
   6:     Console.WriteLine("Service Returned : {0}", strValue);
   7: }
   8: catch (FaultException<MyServiceFault> serviceFault)
   9: {
  10:     Console.WriteLine("Oops..Some error occured!");
  11:     Console.WriteLine("Error Name : {0}",
  12:                 serviceFault.Detail.FaultName);
  13:     Console.WriteLine("Error Message : {0}",
  14:                 serviceFault.Detail.FaultMessage);
  15: }

 

Even though this seems to be a simple and easy method, it is not that efficient. Some of the problems or issues that we can highlight immediately reading the code above are:

1) There is no generic FaultContract, We need to specify a FaultContract for each of the OperationContract

2) As you can notice in the Client, we are explicitly catching the FaultException of our FaultContract type. This again can be different based on the FaultContract on that particular OperationContract

3) There isn’t a way where the errors are logged in the Service. It can be logged before throwing the FaultException, but again you have to do it each time you throw!

4) The Client has to anyhow catch other Exceptions that are not FaultExceptions!

So, do we have a good method where we can handle all the errors and send back meaningful messages back to the Client? Yes, we do!

I would go in detail about that in Part 2 🙂

You can download the Part 1 sample below:

 

Write a Comment

Comment

Time limit is exhausted. Please reload the CAPTCHA.