将异常转换为 JSON
在Java 7中,是否有可能将对象转换为Json?Exception
例:
try {
//something
} catch(Exception ex) {
Gson gson = new Gson();
System.out.println(gson.toJson(ex));
}
在Java 7中,是否有可能将对象转换为Json?Exception
例:
try {
//something
} catch(Exception ex) {
Gson gson = new Gson();
System.out.println(gson.toJson(ex));
}
好吧,可以做这样的事情,尽管您不想转换异常对象本身,而是转换它其中的消息,使用您设计的格式,如下所示:
// […]
} 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));
}
与定义 as 建议答案:getStackTrace()
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();
}
从理论上讲,您还可以迭代堆栈跟踪中的元素,并生成如下所示的内容:
{ "NullPointerException" :
{ "Exception in thread \"main\" java.lang.NullPointerException",
{
"Book.java:16" : "com.example.myproject.Book.getTitle",
"Author.java:25" : "at com.example.myproject.Author.getBookTitles",
"Bootstrap.java:14" : "at com.example.myproject.Bootstrap.main()"
}
},
"Caused By" :
{ "Exception in thread \"main\" java.lang.NullPointerException",
{
"Book.java:16" : "com.example.myproject.Book.getTitle",
"Author.java:25" : "at com.example.myproject.Author.getBookTitles",
"Bootstrap.java:14" : "at com.example.myproject.Bootstrap.main()"
}
}
}
您可以像这样迭代异常:
catch (Exception cause) {
StackTraceElement elements[] = cause.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
System.err.println(elements[i].getFileName()
+ ":" + elements[i].getLineNumber()
+ ">> "
+ elements[i].getMethodName() + "()");
}
}