Search This Blog

Thursday, January 2, 2014

Fault Contract In WCF Service

Service that we develop might get error in come case. This error should be reported to the client in proper manner. Basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handlings are technology specific.

By default when we throw any exception from service, it will not reach the client side.
WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract.
To use Fault contract Create a class like WCFException.

[DataContract]
public class WCFException
{
        [DataMember]
        public string Title
        { get; set; }
        [DataMember]
        public string Message
        { get; set; }
        [DataMember]
        public string StackTrace
        { get; set; }
}

then add into the service interface

[OperationContract]
[FaultContract(typeof(WCFException))]
int Multiply(int a, int b);


and in last throw fault exception

try
{
    return a * b;
}
catch (Exception ex)
{
    WCFException wcfex = new WCFException();
    wcfex.Title = ex.Source;
    wcfex.Message = ex.Message;
    wcfex.StackTrace = ex.StackTrace;
    throw new FaultException<WCFException>(wcfex);
}

No comments:

Post a Comment