将异常转换为JSON

时间:2014-03-08 15:18:33

标签: java json exception

在Java 7中,是否有可能将Exception对象转换为Json?

示例:

try {      
    //something
} catch(Exception ex) {     
    Gson gson = new Gson();
    System.out.println(gson.toJson(ex));
}

3 个答案:

答案 0 :(得分:8)

好吧,有可能做类似的事情,虽然你不想转换异常对象本身,而是转换它所包含的消息,使用你设计的格式,如:

// […]
} 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));
}

getStackTrace()定义为建议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();
}

答案 1 :(得分:7)

理论上,您还可以迭代堆栈跟踪中的元素并生成如下所示的内容:

{ "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()"
        }
    }
}

您可以迭代异常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() + "()");
    }
}

答案 2 :(得分:1)

以下是以标准化方式将Exception转换为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上的博客文章