簡體   English   中英

HTTP承諾 - 處理錯誤

[英]HTTP Promise - Handling Errors

我試圖找到一種處理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));
      });
  };

我的想法是,我可以輕松處理所有錯誤(我們假設除了200錯誤之外),在catch中。 問題是response.json()返回一個promise,因此將它分配給error.response是行不通的。 我需要跟蹤http狀態代碼和響應正文。

這個怎么樣:

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