提问者:小点点

从ajax调用的spring控制器返回错误消息字符串的最佳实践是什么?


我有一个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调用错误函数中正确地获得这个值?


共2个答案

匿名用户

Ajax回调处理程序依赖于http状态代码。除了200之外,OK将触发错误回调。对于每个http状态代码,您可能有不同的错误处理程序。此外,在出现错误的情况下,返回非200 OK代码总是可取的。

请在以下链接中找到示例:如何在一个返回字符串的spring MVC@ResponseBody方法中响应HTTP 400错误?

匿名用户

好的,在学习了一些知识之后,我发现,如果在为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()); 
}