Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Exception to JSON

Is it possible, in Java 7, to convert an Exception object into Json?

example:

try {      
    //something
} catch(Exception ex) {     
    Gson gson = new Gson();
    System.out.println(gson.toJson(ex));
}
like image 568
user2803095 Avatar asked Mar 08 '14 15:03

user2803095


1 Answers

well, it is possible to do something like that, though you don't want to convert the exception object itself, but rather the message it has within, with a format you design, something like:

// […]
} catch (Exception ex) {
    Gson gson = new Gson();
    Map<String, String> exc_map = new HashMap<String, String>();
    exc_map.put("message", ex.toString());
    exc_map.put("stacktrace", getStackTrace(ex));
    System.out.println(gson.toJson(exc_map));
}

with getStackTrace() defined as suggests that answer:

public static String getStackTrace(final Throwable throwable) {
     final StringWriter sw = new StringWriter();
     final PrintWriter pw = new PrintWriter(sw, true);
     throwable.printStackTrace(pw);
     return sw.getBuffer().toString();
}
like image 74
zmo Avatar answered Oct 11 '22 07:10

zmo