【问题标题】:Axios interceptor - error not returned to "then" methodAxios 拦截器 - 错误未返回到“then”方法
【发布时间】:2019-01-26 13:00:07
【问题描述】:

我调用了一个api方法,当响应为500服务器错误时,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);
});

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    您需要使用.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);
    })
    

    【讨论】:

    • 哦,是的,我没想到。谢谢!
    猜你喜欢
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 2019-10-04
    • 1970-01-01
    • 2018-03-03
    • 2021-08-06
    相关资源
    最近更新 更多