在 React 中处理 Axios 错误

新手上路,请多包涵

我有一个调用函数 getAllPeople 的 React 组件:

 componentDidMount() {
   getAllPeople().then(response => {
      this.setState(() => ({ people: response.data }));
    });
  }

getAllPeople 在我的 api 模块中:

 export function getAllPeople() {
  return axios
    .get("/api/getAllPeople")
    .then(response => {
      return response.data;
    })
    .catch(error => {
      return error;
    });
}

我认为这是一个非常基本的问题,但假设我想处理我的根组件中的错误(在我的 componentDidMount 方法中),而不是在 api 函数中,这个根如何组件知道我的 axios 调用是否返回错误?即处理来自 axios 承诺的错误的最佳方法是什么?

原文由 GluePear 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

getAllPeople 函数已经从您的 axios 调用返回数据或错误消息。因此,在 componentDidMount 中,您需要检查对 getAllPeople 的调用的返回值,以确定返回的数据是错误还是有效数据。

 componentDidMount() {
   getAllPeople().then(response => {
      if(response!=error) //error is the error object you can get from the axios call
         this.setState(() => ({ people: response}));
      else { // your error handling goes here
       }
    });
  }

如果你想从你的 api 返回一个承诺,你不应该解决你的 axios 在 api 调用返回的承诺。相反,您可以执行以下操作:

 export function getAllPeople() {
  return axios.get("/api/getAllPeople");
}

然后你可以解决 componentDidMount

 componentDidMount() {
   getAllPeople()
   .then(response => {
         this.setState(() => ({ people: response.data}));
     })
   .catch(error => {
         // your error handling goes here
     }
  }

原文由 palsrealm 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 Promise catch 方法* 处理 API 错误的 更好方法。

 axios.get(people)
    .then((response) => {
        // Success
    })
    .catch((error) => {
        // Error
        if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            // console.log(error.response.data);
            // console.log(error.response.status);
            // console.log(error.response.headers);
        } else if (error.request) {
            // The request was made but no response was received
            // `error.request` is an instance of XMLHttpRequest in the
            // browser and an instance of
            // http.ClientRequest in node.js
            console.log(error.request);
        } else {
            // Something happened in setting up the request that triggered an Error
            console.log('Error', error.message);
        }
        console.log(error.config);
    });

原文由 Sagar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进