【发布时间】:2017-03-23 13:48:11
【问题描述】:
我正在尝试使用 AngularJS + Spring4 开发一个 Web 应用程序。
我想做什么:
1.如果http请求成功,需要将响应数据发送为JSON
2.如果发生异常,需要发送自定义错误信息(将在警告框中显示给用户)
弹簧控制器类:
@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 中解析这个错误信息?这是从春天发送错误消息的正确方法吗?
如果我也在同一个 JSON“responseJSONStr”中发送错误消息,它将是 AngularJS 的成功处理程序中的进程,因为在这种情况下,响应将被视为成功。
任何指导都会非常有帮助。在此先感谢:)
【问题讨论】:
-
成功路径做这个 JSONUtilities.toJson(responseJSON); -> 到 JSON 这些东西对你有什么作用? response.sendError(e.getErrorCode(), e.getErrorMessage());即一种情况将您的响应转换为 Json,而另一种情况似乎没有这样做,或者
-
1.这会给我一个 Json 字符串。 2. 是的,我想将错误消息发送到 UI 并将其显示给用户。如果我在相同的“responseJSONStr”中发送该错误消息,它将进入 AngularJs 中的成功块,所以我这样写..
-
@7663233 有什么方法可以告诉 AngularJS 从服务器发送的“responseJSONStr”JSON 中读取 http 状态??
标签: javascript java angularjs spring spring-mvc