将异常转换为JSON
在Java 7中是否可以将Exception
对象转换为Json?
例:
try { //something
} catch(Exception ex) {
Gson gson = new Gson();
System.out.println(gson.toJson(ex));
}
回答:
从理论上讲,您还可以遍历堆栈跟踪中的元素并生成如下内容:
{ "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() + "()");
}
}
以上是 将异常转换为JSON 的全部内容, 来源链接: utcz.com/qa/403752.html