我调用一个api方法,当响应为500服务器错误时,axios拦截器函数启动,并返回 Promise.reject(error);
但它停在那里,所以“then”函数永远不会运行。相反,它变成“未捕获”:
Uncaught (in promise) Error: Request failed with status code 500
Run Code Online (Sandbox Code Playgroud)
拦截器不应该将错误返回给进行 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);
});
Run Code Online (Sandbox Code Playgroud)
您需要使用.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);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2950 次 |
| 最近记录: |