I got an Exception when trying to convert an Exception Object to a Json Text

I got this Exception

Caused by: java.lang.StackOverflowError
    at java.util.ArrayList.get(ArrayList.java:322)[:1.6.0_12]
    at com.google.gson.stream.JsonWriter.peek(JsonWriter.java:354)

when trying to convert an Exception Object to a Json Text as the following code

Exception exception = new Exception("Test");    
String gsonText = gson.toJson(exception);   

Answers


You get a StackOverflowError because the exception's cause instance member variable is initialized to itself. The serializer attempts to traverse the object and never finishes because it keeps following the reference to the cause.

There's a message on the GSON google group describing this problem, the solutions suggested are:

So, you have three (exclusive) choices:

1) If you are serializing your own exceptions, modify all of your exceptions to set the cause to null, or to passed parameter upon constructing.

2) Call initCause(null) on any exceptions returning (null) from getCause() (may end up getting some IllegalStateExceptions here)

3) Write your own Serializer that would call getCause() rather than attempting to dereference "cause" field.

Also, attempting to send serialized exception code over the wire may be somewhat of a unorthodox design choice.

Usually the advice to application developers is to not show stack traces to clients, so I would suggest calling toString on the exception or otherwise mapping the exception to a message on the server-side and send the message instead.


Need Your Help

VS2013 Crashes When Importing Cordova Plugin

cordova

I am using VS2013 and working in a Cordova project. I am attempting to import the BarcodeScanner plugin (https://github.com/wildabeast/BarcodeScanner) but it keeps causing VS to freeze up and event...

django-mptt filter without breaking the tree

django model filter tree mptt

I'm using django-mptt for a Article model in my Django application. If I want to get all Articles which are set to for example hidden, I could do

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.