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'函数。 –
我明白你的意思了,问题是未解决的承诺,我更新了我的答案,上面我认为应该解决你的问题 –
感谢您的解释和解决方案。我尝试了一种不同的方式,但你的解决方案也可以工作。我接受它作为解决方案。 :) –