HTTP Promise - 处理错误

Posted

技术标签:

【中文标题】HTTP Promise - 处理错误【英文标题】:HTTP Promise - Handling Errors 【发布时间】: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 状态代码和响应正文。

【问题讨论】:

尝试拒绝 Promise 而不是抛出错误,可能是:Promise.reject(new Error(response.statusText)) ,developer.mozilla.org/en-US/docs/Web/javascript/Reference/… 会检查一下谢谢 【参考方案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;
    );
  

【讨论】:

啊,我总是无法理解他们。这是有道理的谢谢

以上是关于HTTP Promise - 处理错误的主要内容,如果未能解决你的问题,请参考以下文章

使用 redux-promise 处理 redux 错误的正确方法

如何正确处理 Promise 链中的错误?

在 Node.js + Express 中使用 Promise 处理错误

promise错误处理的三种方法

处理 Promise 中的错误 - Es6

如何在 reducer 中处理 Redux 的 redux-promise 中间件 AJAX 错误?