【问题标题】:Handle Error response React.js处理错误响应 React.js
【发布时间】:2017-07-03 09:54:21
【问题描述】:

我的 Spring boot Controller 方法:

@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 动作处理器类有如下方法:

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 在我的一个实用程序类中定义为:

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 获得的自定义消息设置为错误对象。我尝试了很多选项,但无法正常工作。

【问题讨论】:

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


    【解决方案1】:

    问题是如何解决 Promise,或者说,当您尝试使用它时没有解决。对“response.json()”的调用会返回一个 Promise,在正常执行流程中,当您不“抛出”错误时,该 Promise 已解决,您可以使用结果。

    但是,当错误被抛出时,你需要解决,或者'.then()'在catch块中的错误。

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

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

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

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

    这里的'error'是调用'response.text()'创建的未解决的Promise,所以你可以通过将'dispatch'包装在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/

    【讨论】:

    • 我的控制器返回一个 JSON 对象。 {消息:“我的错误消息”}。问题是,当我想在checkStatus 函数中使用此响应对象时,承诺尚未完成(仍处于挂起状态)。所以在响应返回到 fetchJSON 函数之前,我无法使用它。
    • 我明白你的意思,问题是未解决的承诺,我已经更新了上面的答案,我认为应该可以解决你的问题
    • 感谢您的解释和解决方案。我尝试了一些不同的方法,但您的解决方案也可以。我接受它作为解决方案。 :)
    猜你喜欢
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 2012-01-03
    • 2016-01-24
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多