Java 将异常转换为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22271099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Exception to JSON
提问by user2803095
Is it possible, in Java 7, to convert an Exception
object into Json?
在 Java 7 中,是否可以将Exception
对象转换为 Json?
example:
例子:
try {
//something
} catch(Exception ex) {
Gson gson = new Gson();
System.out.println(gson.toJson(ex));
}
采纳答案by djangofan
In theory, you could also iterate over the elements in a stack trace and generate something that looks like:
理论上,您还可以遍历堆栈跟踪中的元素并生成如下所示的内容:
{ "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()"
}
}
}
You can iterate the exception like this:
您可以像这样迭代异常:
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() + "()");
}
}
回答by zmo
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:
与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();
}
回答by AgilePro
Below is the routine to convert an Exception to JSON in a standardized way:
以下是以标准化方式将异常转换为 JSON 的例程:
public static JSONObject convertToJSON(Throwable e, String context) throws Exception {
JSONObject responseBody = new JSONObject();
JSONObject errorTag = new JSONObject();
responseBody.put("error", errorTag);
errorTag.put("code", 400);
errorTag.put("context", context);
JSONArray detailList = new JSONArray();
errorTag.put("details", detailList);
Throwable nextRunner = e;
List<ExceptionTracer> traceHolder = new ArrayList<ExceptionTracer>();
while (nextRunner!=null) {
Throwable runner = nextRunner;
nextRunner = runner.getCause();
detailObj.put("code", runner.getClass().getName());
String msg = runner.toString();
detailObj.put("message",msg);
detailList.put(detailObj);
}
JSONArray stackList = new JSONArray();
for (StackTraceElement ste : e.getStackTrace()) {
stackList.put(ste.getFileName() + ": " + ste.getMethodName()
+ ": " + ste.getLineNumber());
}
errorTag.put("stack", stackList);
return responseBody;
}
You can find the complete open source library that implements this at: Purple JSON Utilities. This library supports the JSON Objects as well as the exceptions.
您可以在以下位置找到实现此功能的完整开源库: Purple JSON Utilities。该库支持 JSON 对象以及异常。
This produces a JSON structure of this form:
这会产生这种形式的 JSON 结构:
{
"error": {
"code": "400",
"message": "main error message here",
"target": "approx what the error came from",
"details": [
{
"code": "23-098a",
"message": "Disk drive has frozen up again. It needs to be replaced",
"target": "not sure what the target is"
}
],
"innererror": {
"trace": [ ... ],
"context": [ ... ]
}
}
}
This is the format proposed by the OASIS data standard OASIS ODataand seems to be the most standard option out there, however there does not seem to be high adoption rates of any standard at this point.
这是 OASIS 数据标准OASIS OData提出的格式,似乎是最标准的选项,但目前似乎没有任何标准的高采用率。
The details are discussed in my blog post on Error Handling in JSON REST API
详细信息在我关于JSON REST API 中的错误处理的博客文章中讨论