Handling exceptions the right way in WCF (part 1)

Control over exceptions is very important in WCF because exceptions can contain a lot of information about the internals of your service potentially leading to security issues. WCF allows to define not only data, service or message contracts but also fault contracts. Fault contracts are used to materialize potential exceptions in the metadata of your service.

To do that, you just have to declare on your service contract which exception might be raised by a specific method.

Here is a simple service contract :
[ServiceContract]
public interface IService1
{
[OperationContract]
[FaultContract(typeof(SomeFault))]
void DoSomething();
}

Here, we are telling the WCF runtime to expose a fault contract in the service metadata. The object containing the fault detail is named SomeFault. Here is the definition of the SomeFault class :
[DataContract]
public class SomeFault
{
[DataMember]
public String SomeInfo { get; set; }
}

As you see, SomeFault is a data contract. Its use is only to transfer data through the wire, nothing more, nothing less.

Then you just have to throw exceptions of the right type. You may have already noticed that if an exception is thrown on the service side, you get a simple FaultException on the client side.
Now that we have defined a fault contract, the following code demonstrates how to properly throw an exception from the service :
throw new FaultException<SomeFault>(new SomeFault { SomeInfo = "Some useful data" });

We are simply throwing a generic exception based on the fault contract defined earlier.
Then for the client perspective, we will be able to catch the same type of FaultException. For example :
try
{
proxyInstance.DoSomething();
}
catch(FaultException<SomeFault> ex)
{
// SomeInfo is accessible here
Debug.Print(ex.Detail.SomeInfo);
}

This is possible because the proxy generator (either "Add service reference" or svcutil.exe) produces client side equivalents of the fault contract (SomeFault in this case). This was made possible by including the fault contract in the metadata (adding the FaultContractAttribute on the service contract).

Note : it is very important that you deactivate the IncludeExceptionDetailsInFault on the production server to avoid disclosing sensitive exception details (like the stack trace).

Next time we will see how it is possible to automate parts of this process by using the IErrorHandler interface.

Popular posts from this blog

Handling exceptions the right way in WCF (part 2)

Adding a delay before processing Textbox events

Change the deployment URL of a ClickOnce application