How to serialize an exception

When I run the following code:

var ex = new Exception("TEST", new Exception("Sub Exception", new Exception("Sub sub exception")));
using (JsConfig.With())
{
    ex.ToJson().Dump("ServiceStack");
}

JsonConvert.SerializeObject(ex).Dump("Newtonsoft");

I get the following response:

ServiceStack

"TEST" 


Newtonsoft

{"ClassName":"System.Exception","Message":"TEST","Data":null,"InnerException":{"ClassName":"System.Exception","Message":"Sub Exception","Data":null,"InnerException":{"ClassName":"System.Exception","Message":"Sub sub exception","Data":null,"InnerException":null,"HelpURL":null,"StackTraceString":null,"RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":null,"HResult":-2146233088,"Source":null,"WatsonBuckets":null},"HelpURL":null,"StackTraceString":null,"RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":null,"HResult":-2146233088,"Source":null,"WatsonBuckets":null},"HelpURL":null,"StackTraceString":null,"RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":null,"HResult":-2146233088,"Source":null,"WatsonBuckets":null} 

Question: How can I get ServiceStack to properly serialize an exception to include any inner exceptions?

Exceptions, like any other object with cyclical references are not serializable which is why they’re converted to a ResponseStatus DTO which is serialized instead. The Dump() API ignores any properties which contains circular references which is why they’re missing.

So other than populating a DTO and serializing that, you could call .ToString() to view the Exception with StackTraces:

var s = ex.ToString();