When we develop any WCF 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.So when we throw any exception from service, it will not reach the client side.WCF provides the way to handle and convey the error message to client from service using SOAP Fault contract.
We can understand this concept by using following example:
Step(1)Create Interface with datacontract for Fault contract and use [FaultContract(typeof(MyException))] for AddNumber method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFFaultContract
{
[ServiceContract]
public interface IService1
{
[OperationContract()]
[FaultContract(typeof(MyException))]
int AddNumber(int First, int Second);
}
[DataContract()]
public class MyException
{
[DataMember()]
public string ExTitle;
[DataMember()]
public string ExMessage;
[DataMember()]
public string InnerEx;
[DataMember()]
public string StackTrace;
}
}
Step(2) Implements the interface using fault contract as MyException
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFFaultContract
{
public class Service1 : IService1
{
public int AddNumber(int First, int Second)
{
//Do something
MyException MyException = new MyException();
MyException.ExTitle = "Error Funtion:AddNumber()";
MyException.ExMessage = "Error while Adding number in AddNumber function.";
MyException.InnerEx = "Inner exception message from serice";
MyException.StackTrace = "Stack Trace message from service.";
throw new FaultException<MyException>(MyException, "Reason: Testing the SOAP Fault contract");
}
}
}
OR--> Implements using try catch:
public int AddNumber(int First, int Second)
{
try
{
// return 10;
throw new Exception();
}
catch (Exception exx)
{
//Do something
MyException MyException = new MyException();
MyException.ExTitle = "Error Funtion:AddNumber()";
MyException.ExMessage = "Error while Adding number in AddNumber function.";
MyException.InnerEx = "Inner exception message from serice";
MyException.StackTrace = exx.StackTrace; //"Stack Trace message from service.";
throw new FaultException<MyException>(MyException, "Reason: Testing the SOAP Fault contract");
}
}
Step(3) Create Proxy and use it in the client side as bellow
try
{
WCFFaultException.Service1Client proxy = new WCFFaultException.Service1Client();
Console.WriteLine("Client is running at " + DateTime.Now.ToString());
Console.WriteLine("Sum of two numbers... 2+2 =" + proxy.AddNumber(2,2));
Console.ReadLine();
}
catch (FaultException<WCFFaultException.MyException> ex)
{
// Exception Handling code
}
I hope this code will help you.....................................:)
No comments:
Post a Comment