Monday, June 15, 2009

Exception handling in WCF

This is an simple example for how to manage exception in WCF and their client.
WCF returns system exception and application exception during development time.
But hosting time,these kind of exception will not handled by SOAP protocol.
So SOAP friendly exception details must be implemented on service side using FaultContractAttribute.
Generate the custome exception message must be implemented on a class that start preceding with DataContractAttribute.

WCF Source for Exception handling

[ServiceContract]
public interface IService
{
[OperationContract]
[FaultContractAttribute(typeof(FaultContractExceptionTest))]
string GetData(int value);

}
[DataContractAttribute]
public class FaultContractExceptionTest
{
private string Msg;
public FaultContractExceptionTest(string msg)
{
this.Msg = msg;
}
[DataMember]
public string ErrorMessage
{
get { return this.Msg; }
set { this.Msg = value; }
}
}
________________________________________________________________________

Service Implementation Source
_________________________________________________________________________
public class Service : IService
{
public string GetData(int value)
{

if (value == 152)
{
return "Your authentication code is " + value.ToString();
}
else
{
throw new FaultException(new FaultContractExceptionTest("Check your Pass Number"),"Some Problem");
}}}


Client Implementation - Source code - I written on Button click event
ServiceClient sc = new ServiceClient();
try
{

Response.Write(sc.GetData(Convert.ToInt32(TextBox1.Text)));

}

catch (FaultException msgObj)
{
Response.Write(msgObj.Detail.ErrorMessage);
}