1
我的春天啓動控制器的方法:處理錯誤響應React.js
@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<APIResponseMessage> testMethod(@RequestBody MyPojo myPojo) {
APIResponseMessage resp = new APIResponseMessage();
try {
serviceObj.callServiceMethod(myPojo);
resp.setMessage("successfull!");
} catch (Exception e) {
resp.setMessage("failed!");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(resp);
}
return ResponseEntity.ok(resp);
}
行動作出反應處理類有以下方法:
export default (data) => (dispatch) => {
dispatch({
type: initHandler
});
fetchJSON(url, 'POST', data)
.then((json) => {
dispatch({
type: successHandler,
apiResponse: json
})
})
.catch((error) => {
dispatch({
type: failureHandler,
apiResponse: error,
apiMessage : "System encountered error. Please try again later."
})
})
}
而且fetchJSON被定義在我的util類中的一個反應作爲:
export const checkStatus = response => {
const hasError = (response.status < 200 || response.status >= 300)
if (hasError) {
const error = new Error("This is an error") // I want to set my message that I obtained from the controller here.
throw error
}
return response
}
export const parseJSON = response => response.json()
export const fetchJSON = (url, method, data) => {
return fetch(url, {
method: method,
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(data)
}).then(checkStatus).then(parseJSON);
}
我想將我從我的API獲得的自定義消息設置爲erro r對象。我嘗試了很多選擇,但無法使其工作。
我控制器返回JSON對象。 {message:「我的錯誤消息」}。問題在於,當我希望在'checkStatus'函數中使用這個響應對象時,承諾還沒有完成(仍處於未決狀態)。所以我不能玩它,直到響應返回到'fetchJSON'函數。 –
我明白你的意思了,問題是未解決的承諾,我更新了我的答案,上面我認爲應該解決你的問題 –
感謝您的解釋和解決方案。我嘗試了一種不同的方式,但你的解決方案也可以工作。我接受它作爲解決方案。 :) –