The following is the standard procedure for converting an exception to 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 JSON objects as well as exceptions.
This creates the JSON structure of this form:
{ "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 standard for OASIS OData data , and it seems to be the most standard option, but there are still no high rates of adoption of any standard.
Details are discussed in my blog post about error handling in the JSON REST API.
Agilepro
source share