How to Throw an Exception with Complex Types or Data Contracts with a Fault Exception

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

The following steps show an example of how to throw an exception with a data contract that has a complex type.
  1. Define the DataContract type to pass the details of SOAP faults as exceptions from a service back to a client
[DataContract]
public class DatabaseFault
{
[DataMember]
public string DbOperation;
[DataMember]
public string DbReason
[DataMember]
public string DbMessage;
}
  1. Use the FaultContract attribute in the ListCustomers method to generate SOAP faults.
[ServiceContract]
public interface ICustomerService
{
// Get the list of customers
[FaultContract(typeof(DatabaseFault))]
[OperationContract]
List<string> ListCustomers();
…
}
  1. 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);
}

Additional Resources

Last edited Jun 13, 2008 at 7:43 PM by prashantbansode, version 1

Comments

No comments yet.