以下是以标准化方式将异常转换为 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;
}
您可以在以下位置找到实现此功能的完整开源库:Purple JSON Utilities。该库支持 JSON 对象以及异常。
这会产生这种形式的 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": [ ... ]
}
}
}
这是 OASIS 数据标准 OASIS OData 提出的格式,似乎是目前最标准的选项,但目前似乎没有任何标准的高采用率。
详情在我Error Handling in JSON REST API的博文中讨论