简体   繁体   English

HTTP承诺 - 处理错误

[英]HTTP Promise - Handling Errors

I am trying to find a nice way of handling http responses that I consider an error. 我试图找到一种处理http响应的好方法,我认为这是一个错误。 I am using fetch in React Native. 我在React Native中使用fetch Here is my code. 这是我的代码。

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

Then... 然后...

  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;
    }
  },

And the above are called like this: 上面的内容如下所示:

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

The idea is that I can easily handle all the errors separately (we assume anything but 200 error), within the catch. 我的想法是,我可以轻松处理所有错误(我们假设除了200错误之外),在catch中。 The problem is that response.json() returns a promise, so assigning it to error.response is not working. 问题是response.json()返回一个promise,因此将它分配给error.response是行不通的。 I need to keep track of http status code and the response body. 我需要跟踪http状态代码和响应正文。

How about this: 这个怎么样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM