我有一个Spring控制器,我从那里返回一个字符串。基本上,我使用JSONObject和JSONArray,最后生成一个字符串并返回它。像这样:
@RequestMapping(value = "getValue")
public @ResponseBody
String getValue(){
JSONObject jassonObject = new JSONObject();
JSONArray jassonArray = new JSONArray();
jassonObject.put("mykey",jassonArray);
And finally:
return jassonObject.toString();
}
但是假设在生成此JSONObject时,如果我遇到任何异常,我想返回该异常消息。这就是:
try {
JSONObject jassonObject = new JSONObject();
JSONArray jassonArray = new JSONArray();
jassonObject.put("mykey",jassonArray);
return jassonObject.toString();
} catch(Exception ex) {
return the exception?
}
我的问题是,如何正确地将这个异常值作为错误返回,并从ajax调用错误函数中正确地获取它?
发布于 2018-04-12 07:40:41
Ajax回调处理程序依赖于http状态代码。超过200 OK将触发错误回调。每个http状态代码可能有不同的错误处理程序。此外,在出现错误时,建议始终返回非200 OK代码。
请在以下链接中找到示例:How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?
发布于 2018-04-23 04:43:05
好吧,在学习了一些之后,我发现,在为Ajax请求生成JSONObject时出现异常的情况下,我们应该用http Bad request响应代码进行响应。就像我的例子:
try {
JSONObject jassonObject = new JSONObject();
JSONArray jassonArray = new JSONArray();
jassonObject.put("mykey",jassonArray);
return jassonObject.toString();
} catch(Exception ex) {
jassonObject.put("errorMessageKey", e.getMessage()); // generating
//json object with error message
response.setStatus(400); // bad request
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jassonObject.toString());
}
https://stackoverflow.com/questions/49788606
复制