IT虾米网

reactjs之在 React 中处理 Axios 错误

tintown 2025年12月25日 程序员 40 0

我有一个调用函数 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 调用是否返回错误? IE。处理来自 axios Promise 的错误的最佳方法是什么?

请您参考如下方法:

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


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!