Fault Handling in WCF

Retired Content

The Web Service Software Factory is now maintained by the community and can be found on the Service Factory site.

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies.
This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

Retired: November 2011

The default configuration of WCF protects sensitive data from exposure by not sending SOAP fault messages to the client application when an unhandled exception occurs. You can override this behavior by adding a serviceDebug element to the service behavior that is associated with a WCF service in the configuration file. To enable support for unhandled exceptions, an attribute named includeExceptionDetailInFaults should be set to true in the serviceDebug element. This configuration should be used only in a development environment; it is not recommended for service deployment.

Ideally, a service should never allow unhandled exceptions to be returned to a client application, regardless of the serviceDebug configuration. To prevent unhandled exceptions, the recommended approach is to always catch exceptions in the service implementation and return a FaultException as necessary. There are two ways that FaultExceptions can be used; one approach is to wrap an exception that was caught, which returns full exception details, and the other approach is to use a DataContract to define the error data that can be returned. The approach of wrapping an existing exception inside a FaultException is also not recommended because sensitive data will be returned to the client application, regardless of configuration settings.

The serviceDebug element and associated includeExceptionDetailInFaults attribute is applicable only to unhandled exceptions. If you throw a FaultException in a WCF service, the associated error information is sent to the client application, regardless of the settings in serviceDebug.

The DataContract that can be used with a FaultException is also referred to as a FaultContract, which can be associated with service operations using the FaultContractAttribute. The use of FaultContracts provides information that service client applications can use to appropriately handle errors. Typical deployed services use the FaultContractAttribute to formally specify all exceptions that a client application can expect to receive in the normal course of operation.

The end result is that you have three main options when it comes to handling exceptions and returning exception information. The following How-to topics provide more information about implementing these different options: