-->

Wednesday 17 August 2011

Fault Contracts in WCF services

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<MyService.CustomException> ex)
        {
        //Process the Exception as thrown
        }

1 comment: