我正在尝试使用AngularJS + Spring4开发Web应用程序。
我想做什么:
1.如果 http 请求成功,需要以 JSON
形式发送响应数据2.In 异常的情况下,需要发送自定义错误消息(将在警报框中向用户显示(
弹簧控制器类:
@RequestMapping(value = "/loadAllUsers", method = RequestMethod.POST)
@ResponseBody
public String loadAllUsers(@RequestBody String paramsJsonStr,ModelMap model,HttpServletRequest request, HttpServletResponse response) throws IOException {
String responseJSONStr = null;
ResponseJSON responseJSON = new ResponseJSON(); //Custom class for sending response data
try {
.....
.....
List<User> users = this.loadAllUsers();
responseJSON.setIsSuccessful(true);
responseJSON.setData(schemas);
responseJSONStr = JSONUtilities.toJson(responseJSON);
}catch (CustomException e) {
e.printStackTrace();
response.sendError(e.getErrorCode(), e.getErrorMessage());
}
return responseJSONStr;
}
AngularJs 控制器:
$http.post("loadAllUsers",{})
.success(function(data){
console.log('success handler');
console.log(data);
})
.error(function(error) {
console.log('error handler');
console.log(error);
console.log(error.status);
console.log(error.data);
console.log(error.statusText );
console.log(error.headers);
console.log(error.config);
})
问题: 无法读取错误消息,但能够读取成功数据。
当我在控制台中打印错误时,我收到此 HTML 标记:
<html><head><title>Error</title></head><body>Invalid input.</body></html>
如何在 AngularJS 中解析此错误消息?这是从 spring 发送错误消息的正确方法吗?
如果我也在同一 JSON "responseJSONStr" 中发送错误消息,它将是 AngularJS 的成功处理程序中的进程,因为在这种情况下响应将被视为成功。
任何指导都将非常有帮助。提前致谢:)
如果将来有人尝试这样做,这可能会有所帮助。为此,可以使用"response.setStatus"设置失败状态代码,而不是使用"response.sendError",并且可以在responseJSON中将错误消息设置为"false",如下所示
@RequestMapping(value = "/loadAllUsers", method = RequestMethod.POST)
@ResponseBody
public String loadAllUsers(@RequestBody String paramsJsonStr,ModelMap model,HttpServletRequest request, HttpServletResponse response) throws IOException {
String responseJSONStr = null;
ResponseJSON responseJSON = new ResponseJSON(); //Custom class for sending response data
try {
.....
.....
List<User> users = this.loadAllUsers();
responseJSON.setIsSuccessful(true);
responseJSON.setData(schemas);
}catch (CustomException e) {
e.printStackTrace();
response.setStatus(e.getErrorCode()); //http failure status code as per respective error
responseJSON.setIsSuccessful(false);
responseJSON.setMessage(e.getErrorMessage());
}
responseJSONStr = JSONUtilities.toJson(responseJSON);
return responseJSONStr;
}