处理错误响应React.js

时间:2017-07-03 09:54:21

标签: reactjs spring-boot error-handling react-redux

我的Spring启动控制器方法:

@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);
    }

React action handler类具有以下方法:

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获取的自定义消息设置为错误对象。我尝试了很多选项,但无法使其发挥作用。

1 个答案:

答案 0 :(得分:1)

问题是如何解决Promise,或者更确切地说,当您尝试使用Promise时未解决。致电&#39; response.json()&#39;在正常的执行流程中,当你没有“扔掉”时,你会回复一个承诺。错误,此承诺已解决,您可以使用结果。

然而,当抛出错误时,您需要解决,或者&#39; .then()&#39; catch块中的错误。

我认为这应该对你有用,首先在checkStatus函数中抛出你的response.text():

if (hasError) {
    throw response.json()
}

由于您在Promise中抛出错误,因此会调用最近的catch或reject回调:

.catch((error) => {
  dispatch({
    type: failureHandler,
    apiResponse: error,
    apiMessage : "System encountered error. Please try again later."
  })
})

&#39;错误&#39;在这种情况下,通过调用&#39; response.text()&#39;创建了未解决的Promise,因此您可以通过包装&#39; dispatch&#39;来解决此问题。在error.then()中如下:

.catch((error) => { // error is a Promise
    error.then((e) => {
        dispatch({
          type: failureHandler,
          apiResponse: e, // e is now the resolved value of 'response.text()'
          apiMessage : "System encountered error. Please try again later."
        });
    });
})

这里有一个简化的jsfiddle:https://jsfiddle.net/LLL38vea/