Exception serialization & WCF


I was helping a colleague of mine this week with some exception handling in WCF. The problem we were facing was that when we send a faultexception we lost important information about the original exception like the innerexceptions. Although it may not be best practice to send all of the exception information to the client we still wanted to find a way to get this done.

We tried various possibilities and ended up with the binary serialization of the original exception. To send it to the client we converted the serialized exception to a base64 string which is ideal for this sort of scenario’s. Then on the client side we just deserialize the base64 string back into an exception. We still use the WCF faultexception but we use the reason property to store the base64 string for transport.

We also tried the XML serialization but this gave to much trouble on the data property of the exception class because it was marked not-serializable due to the IDictionary interface it implements.

Another thing we looked at was using reflection to rebuilt the exception, but this was too complex and can cause a performance overhead.

Below you can see a sample of the ExceptionFormatter class that we created. Actually it’s nothing more than regular binary serialization with the constraint that the serialized object must implement the ISerializable interface. Oh yes mind the line breaks !

Imports System.Runtime.Serialization.Formatters.Binary

Public Class ExceptionFormatter

Public Sub New()
End Sub

Public Function Serialize(ByVal objectToSerialize As     Runtime.Serialization.ISerializable) As String
Dim formatter As New BinaryFormatter
Dim mem As New IO.MemoryStream
formatter.Serialize(mem, objectToSerialize)
Return Convert.ToBase64String(mem.ToArray)
End Function

Public Function Deserialize(ByVal base64String As String)     As Runtime.Serialization.ISerializable
Dim formatter As New BinaryFormatter
Return formatter.Deserialize(New IO.MemoryStream(        Convert.FromBase64String(base64String)))
End Function
End Class

  • http://flipbitsnotburgers.blogspot.com/ Andrew Badera

    Hello-

    Interesting work … but do you have to explicitly serialize and deserialize in order to throw the exception over the service boundary? If so, what sort of pattern have you implemented?

  • Jeff

    Have you tried using DataContractSerializer to serialize your exception? Essentially that is what WCF would be using underneath if you were to create your own exception type that inherits form FaultException and exposed a publish property called something like RealException.

  • http://suncat2000.myopenid.com/ GetSmart

    How did you get WCF to use your formatter when returning exceptions?