Saturday, June 7, 2008

WCF Exception handling


Exception handling

We could do a simple exception handling from client application. One of the most basic ways of exception handling in the application is given below

try
{
HelloIndigoService.HelloIndigoServiceClient hisc = new HelloIndigoClient.HelloIndigoService.HelloIndigoServiceClient("HelloIndigoNetTcpEndPoint");
Console.WriteLine(hisc.SayHello("Hello Indigo"));
Console.ReadKey(true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Inner Exception: ");
Console.WriteLine(ex.InnerException.Message);
Console.ReadKey(true);
}

Error handling as in the above code would only give WCF error. If there are any errors within the code, it might not get passed on to the client system.

To implement exception handling service code needs to be changed to as mentioned below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace HelloIndigo
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
[ServiceContract]
public interface IHelloIndigo
{
[OperationContract]
string SayHello(string sName);

[OperationContract]
int GetSquare(int nNum);

[FaultContract(typeof(ConfigFault))]
[OperationContract]
int GetCube(int nNum);

// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations

[DataContract]
public class ConfigFault
{
[DataMember]
public string ConfigOperation;
[DataMember]
public string ConfigReason;
[DataMember]
public string ConfigMessage;
}
}

ConfigFault class is the one that will be populate with appropriate error message and shared with client

WCF Functions cannot throw error messages through ConfigFault unless explicitly told as in the case of the function GetCube in the above code

Let’s see the implantation of GetCube

public int GetCube(int nNum)
{
//handle exception here
if (nNum >= 1 nNum < 1000)
{
ConfigFault cf = new ConfigFault();
cf.ConfigMessage = "Only positive numbers < 1000 are allowed";
cf.ConfigOperation = "GetCube";
cf.ConfigReason = "Number Exception";
throw new FaultException(cf);
}
return (nNum * nNum * nNum);
}

Having seen GetCube function implementation let’s take a look at the client side code changes

try
{
hic.GetCube(-3);
}
catch (FaultException cf)
{
Console.WriteLine(cf.Detail.ConfigMessage);
Console.WriteLine(cf.Detail.ConfigOperation);
Console.WriteLine(cf.Detail.ConfigReason);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}


Obviously this way of handling errors is more informative than normal way.

I’ll see you with more updates

No comments: