Handling WCF FaultExceptions with SilverLight 3

Silverlight 3 Introduced the capability of handling WCF fault exceptions.

Using FaultContracts is a good way of managing and shielding WCF exceptions, but I also wanted the silverlight client to be able to:

  • Catch generic CLR exceptions and propagate them to the client as a generic fault exceptions.
  • Catch some application specific exceptions and propagate these to the client as a general fault so that I can build the logic around the client to escalate the the cause that raised the exception in runtime.
  • Log any unhandled exceptions that may sneak there way up to the services.

Whenever sensitive data is involved create a fault exception and pass the error data to the client sufficient enough to build the logic around the client to handle the fault senario

WCF provides great exception shielding by default, but we wanted a bit more control. This is where WCF IErrorHandler interface allows you to intercept any faults or exceptions before they are sent back to the client. To use this properly, you still need to define your FaultContract as required for expected exceptions.

However By default, WCF services return fault messages with an HTTP 500 response code. Due to limitations in the browser networking stack, the bodies of these messages are inaccessible within Silverlight 3 , and consequently the fault messages cannot be read by the client.

To send faults to a Silverlight client that are accessible to it, an WCF service must modify the way it sends its fault messages. The key change needed is for WCF to return fault messages with an HTTP 200 response code instead of the HTTP 500 response code. This change enables Silverlight to read the body of the message and also enables WCF clients of the same service to continue working using their normal fault-handling procedures.

The modification on the server can be made by defining a WCF endpoint behavior for Silverlight faults. Then this behavior can be enforced either by service contract declarative style or via configuration. More details about this can be found here

The attached sample Silverlight project shows how message behaviour extensions,Fault contracts and IErrorHandler interfaced is used to achieve the above requirement.