【问题标题】:HTTP Promise - Handling ErrorsHTTP Promise - 处理错误
【发布时间】:2016-09-29 06:17:48
【问题描述】:

我正在尝试找到一种处理我认为错误的 http 响应的好方法。我在 React Native 中使用 fetch。这是我的代码。

loginRequest(url) {
  return fetch(url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;'
    },
    ....
  })
  .then(response => {
    return this.processResponse(response);
  });
}

那么……

  processResponse(response) {
    if (response.status === 200) {
      return response.json();
    } else {
      let error = new Error(response.status);
      error.response = response.json(); // This is the problem
      error.status = response.status;
      throw error;
    }
  },

上面是这样调用的:

    return ApiRequests.loginRequest(username, password)
      .then(json => {
        dispatch(Actions.loginSuccess(json, username, password));
      })
      .catch(error => {
        dispatch(Actions.loginFailure(error));
      });
  };

我的想法是我可以在 catch 中轻松地分别处理所有错误(我们假设除了 200 错误之外的任何错误)。问题是 response.json() 返回一个承诺,因此将其分配给 error.response 不起作用。我需要跟踪 http 状态代码和响应正文。

【问题讨论】:

标签: javascript react-native fetch es6-promise


【解决方案1】:

这个怎么样:

processResponse(response) {
  if (response.status === 200) {
    return response.json();
  } else {
    return response.json().then((data) => {
      let error      = new Error(response.status);
      error.response = data;
      error.status   = response.status;
      throw error;
    });
  }
}

【讨论】:

  • 啊,我总是无法理解他们。这是有道理的谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
  • 2019-01-05
  • 2014-06-21
  • 2016-01-10
相关资源
最近更新 更多