首页 > 解决方案 > Axios 拦截器 - 错误未返回到“then”方法

问题描述

我调用了一个api方法,当响应为500 server error时,axios拦截器函数启动,并返回 Promise.reject(error);

但它停在那里,所以“then”函数永远不会运行。相反,它变成了“未捕获”:

Uncaught (in promise) Error: Request failed with status code 500

拦截器不应该将错误返回给进行 api 调用的函数,然后我可以在那里处理错误吗?

这是代码:

    //on submitting form
    onSubmit(data){

           //call api function
          api.sendPayment(data).then(response => {

                //this never runs
                 alert('response!')
                console.log(JSON.stringify(response))
            }    


    });


//Api function
sendPayment: (formData) => {

        return axios.post('/api/checkout', formData);
    },

//interceptor

axios.interceptors.response.use(response => {
    return response;
}, error => {

    //this executes the "uncaught" error instead of returning to the "then" function.
    return  Promise.reject(error);
});

标签: reactjsaxios

解决方案


您需要使用.catch. 错误不会被捕获.then

api.sendPayment(data).then(response => {
    //this never runs
        alert('response!')
    console.log(JSON.stringify(response))
}).catch(err => {
    //Handle your error here
    console.log(err.response);
})

推荐阅读