WCF FaultHandling

01. December 2013 WCF 0

The WCF service cannot return a .NET exception to the client. The WCF service and the client communicate by passing SOAP messages. If an exception occurs, the WCF runtime serializes the exception into XML and passes that to the client.

By default, the service does not send any information explaining what happened. WCF does not reveal details about what the service does internally. This makes the service more secure.

WCF services provide a very nice abstraction over these in form of FaultException and the services can easily propagate the exception information to the client using the FaultException and FaultContract.

Throw a FaultException in the Service Implementation

public int Divide(int num1, int num2)
{
    try
    {
        return num1 / num2;
    }
    catch (DivideByZeroException ex)
    {
        throw new FaultException(ex.Message);
    }
}

WCF services also provides a way for us to throw custom objects in our fault exceptions. These custom objects will contain the detailed information about the exception. These objects will have to be exposed as the FaultContract from the service.

[DataContract]
public class MyExceptionContainer
{
    [DataMember]
    public string Messsage { get; set; }
    [DataMember]
    public string Description { get; set; }
}

Throw this type of exception in the service implementation:

public int Multiply(int num1, int num2)
{
    if (num1 == 0 || num2 == 0)
    {
        MyExceptionContainer exceptionDetails = new MyExceptionContainer();
        exceptionDetails.Messsage = "Business Rule violatuion";
        exceptionDetails.Description = "The numbers should be non zero to perform this operation";
        throw new FaultException<MyExceptionContainer>(exceptionDetails);
    }
 
    return num1 * num2;
}

And catch it in the application code:

try
{
    using (ServiceReference1.TestServiceClient client = new ServiceReference1.TestServiceClient())
    {
        int num1 = 6;
        int num2 = 3;
        int resultMulitply = client.Multiply(num1, 0);
        int resultDivide = client.Divide(num1, num2);
 
        Console.WriteLine("Multiplication: {0}, Division: {1}", resultMulitply, resultDivide);
    }
 
    Console.ReadLine();
}
catch (FaultException<ServiceReference1.MyExceptionContainer> ex)
{
    Console.WriteLine(ex.Detail.Messsage);
    Console.WriteLine(ex.Detail.Description);
}
catch (FaultException ex)
{
    Console.WriteLine(ex.Message);
}

Further Reading


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.