繁体   English   中英

无法读取错误消息:AngularJS-Spring 4

[英]Couldn't read error message : AngularJS - Spring 4

我正在尝试使用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中解析此错误消息? 这是从Spring发送错误消息的正确方法吗?

如果我也以相同的JSON“ responseJSONStr”发送错误消息,它将是AngularJS成功处理程序中的进程,因为在这种情况下,响应将被视为成功。

任何指导都将非常有帮助。 提前致谢 :)

如果将来有人尝试这样做,可能会有所帮助。.要实现此目的,可以使用“ response.setStatus”设置故障状态代码,而不是使用“ response.sendError”,并且可以使用isSuccessful在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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM