Wcf Fault Contract

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.

In order to support interoperability and client will also be interested only, what wents wrong? not on how and where cause the error.

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.

For Example :

In IService1 :

[ServiceContract]
public interface IService1
{
[OperationContract]
[FaultContract(typeof(MyException))]
int Divide(int a, int b);
}

[DataContract]
public class MyException
{
[DataMember]
public string MyError { get; set; }
}

In Service1 Class :

public class Service1 : IService1
{
public int Divide(int a, int b)
{
try
{
Console.WriteLine(“in divide… “);
return a / b;
}
  catch (Exception ex)
            {
                MyException exobj = new MyException();
                exobj.MyError = ” Error by human….” + ex.Message;
                throw new FaultException<MyException>(exobj) ;
            }
}
}

In Client :

static void Main(string[] args)
{
ServiceReference1.Service1Client client = new ConsoleClient.ServiceReference1.Service1Client();
try
{
Console.WriteLine(client.Divide(12, 0));
}
catch (FaultException<ServiceReference1.MyException> myobj)
            {
                Console.WriteLine(myobj.Message);
                Console.WriteLine(“—-“);
                Console.WriteLine(myobj.Detail.MyError);
                Console.WriteLine();
            }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s