私の春のブートコントローラ方法:ハンドルエラー応答React.js
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のクラスのいずれかで定義される:
@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 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オブジェクトを返します。 {メッセージ: "私のエラーメッセージ"}。この問題は、 'checkStatus'関数でこのレスポンスオブジェクトを使用するときまでに、約束が完了していない(保留状態のままです)ためです。だから、応答が 'fetchJSON'関数に返されるまで、私はそれを試してみることができません。 –
私はあなたが意味するものを見て、問題は未解決の約束です、私はあなたの問題を解決すべきだと思う以上の私の答えを更新しました –
説明と解決に感謝します。私は少し違った方法を試しましたが、あなたのソリューションも機能します。私はそれを解決策として受け入れています。 :) –