Use a fault contract to return error information to clients

J.D. Meier, Jason Taylor, Prashant Bansode, Carlos Farre, Madhu Sundararajan, Steve Gregersen.

Use a fault contract to define the exceptions in your service and return error information to clients. By using the FaultContract attribute in a service contract you can specify the possible faults that can occur in you WCF service. If there is an exception in your WCF service operation, use the FaultContract attribute to generate a specific SOAP fault message that will be sent back to the client application.

The FaultContract attribute can only be used in operations that return a response. You cannot use this attribute on a one-way operation.

The following code snippet shows how to use the FaultContract attribute to return error information.
1. Define the type to pass the details of SOAP faults as exceptions from a service back to a client
public class DatabaseFault
    public string DbOperation;
    public string DbReason
    public string DbMessage;

2. Use the FaultContract attribute in the ListCustomers method to generate SOAP faults.
public interface ICustomerService
    // Get the list of customers
    List<string> ListCustomers();

3. Create and populate the DatabaseFault object with the details of the exception in the Service implementation class and then throw a FaultException object with the DatabaseFault object details.
catch(Exception e)
{    DatabaseFault df = new DatabaseFault();
    df.DbOperation = "ExecuteReader";
    df.DbReason = "Exception in querying the Northwind database.";
    df.DbMessage = e.Message;
    throw new FaultException<DatabaseFault>(df);

Last edited Apr 16, 2008 at 11:31 PM by prashantbansode, version 1


lerocha Jul 22, 2009 at 5:09 PM 
A suggestion when throwing the fault exception is to specify the fault reason. If you do not specify it, the fault exception will say that "The creator of this fault did not specify a Reason.". In order to specify a reason, change the following line from:

throw new FaultException<DatabaseFault>(df);


throw new FaultException<DatabaseFault>(df, df.DbReason);