Axios拦截器-错误未返回“ then”方法

时间:2018-08-20 11:43:17

标签: reactjs axios

我调用一个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);
});

1 个答案:

答案 0 :(得分:3)

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