【问题标题】:Break axios promise chain on catch()在 catch() 上打破 axios 承诺链
【发布时间】:2020-03-31 01:33:55
【问题描述】:

我已将所有 API 调用集中在一个唯一的文件 API.js 中,如下所示:

API.js

Class APIContextProvider extends Component {

    async apiCallTest() {

        var url = random_url

        const options = {
            url: url,
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;',
            },
        };

        return await axios(options)
            .then(response => {
                if (response.status === 200) {
                    return response.data
                }
            }).catch(error => {
                console.log(error.response.status)
            }
        );;
    }

然后我从另一个组件调用我的 API:

OutsideClass.js

async componentDidMount() {
    this.context.apiCallTest().then(data => {
        // How can I prevent this then() to run when catch() happens?
    });
}

一切完成的顺序是:then().catch().then()。

我想要的是防止最后一个 then()。如果捕获到特定错误(如 401),则不会发生,因为我想要全局错误处理。

四处寻找,但找不到解决方案......

谢谢!

【问题讨论】:

  • 你不能有全局错误处理,每个promise链都需要单独处理。
  • 为了防止then回调执行,重新抛出一个错误。

标签: reactjs promise axios


【解决方案1】:

如果你想全局捕获异常,那么在你的引导文件中使用 axios 拦截器

window.axios = require('axios'); 
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

axios.interceptors.response.use(
function (response) { 
    return response; 
},
function (error) {
    // handle error
    if (error.response.status === 422) 
        return error;        
    if (error.response.status === 401) 
        alert(error.response.status + ': ' + error.response.data.message);               
});

【讨论】:

    【解决方案2】:

    你可以在你的catch中再次抛出错误,它会避开then并进入下一个catch。

    await axios(options)
                .then(response => {
                    if (response.status === 200) {
                        return response.data
                    }
                }).catch(error => {
                    if (error.response.status === 401) { 
                      throw error;
                    }
                    console.log(error.response.status)
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-23
      • 2017-11-23
      • 2018-02-06
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 2016-04-17
      相关资源
      最近更新 更多