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