簡體   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