reactjs - 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);
});
解决方案
您需要使用.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);
})
推荐阅读
- c++ - mySQL C++ 连接器 Visual Studio 2017
- c++ - Makefile 没有按照我的说法构建对象
- java - 获取移动设备 Android 或 iOS 屏幕的真实物理尺寸?
- .net - 如何为 .Net 项目设置哨兵
- c# - 如何在 Visual Studio IOS 中更改为另一个视图控制器(解释清楚)
- json - json-glib:未定义对“json_parser_new”collect2 的引用错误:ld 返回 1 退出状态
- git - 如何允许另一个用户从 GIT 中的原点拉取
- java - 将 HTTPResponse 正文中的字节流转换为 pdf 文件
- jquery - 谷歌图表甘特图在顶部显示 x 轴(日历)
- vba - excel宏范围使用单元格错误