WCF

WCF – Exception Handling in Asynchronous Operations

Yesterday, I got a query regarding how to handle exceptions in case of asynchronous web service operations. Precise question was,

I am calling a WCF service using Asynchronous way,  the service may execute for some time, meanwhile if any exception occurred in the service side how can I come to know what happened in the service side?

I am not able to get the status in the Async Method.

There is a pretty simple solution available for this problem.

When the asynchronous method throws an exception, proxy catches it and when the client calls End Operation the proxy re-throws that exception object so that client can handle the exception. If a COMPLETION CALLBACK is provided, WCF calls that method immediately after the exception is received. Exception thrown is compliant with the fault contract and type of exception. Following code snippet shows how to do this;

Contract Code

public interface ICalculator
{
[OperationContract]
[FaultContract(typeof(Exception))]
double Add(double n1, double n2);
}

Service Code

public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
throw new FaultException(new Exception("Gaurav is sending exception"));
return n1 + n2;
}
}

Client Code

class Client
{
static void Main()
{
Console.WriteLine("Press to terminate client once the output is displayed.");
Console.WriteLine();

GauravCalculator.CalculatorClient calcService = new GauravCalculator.CalculatorClient();
int sum = 0;
AsyncCallback completion = (result) =>
{
try
{
sum = (int)calcService.EndAdd(result);
Console.WriteLine("Sum is :" +sum.ToString());
calcService.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
};
calcService.BeginAdd(10, 10, completion, null);

Console.WriteLine();
}

Using this method you can receive any service side exceptions on client side.

~pEaCe~

Currently Listening to: Bekaraar from Pathshala (new Lucky Ali song)