在catch()上打破axios承诺链

时间:2020-03-30 16:56:26

标签: reactjs promise axios

我将所有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),则会发生这种情况。

无处不在,但找不到解决方案...

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以在捕获中再次抛出错误,这样可以避免then并转到下一个捕获。

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)
            }

答案 1 :(得分: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);               
});