vue.js - 在 vuejs 中使用 axios 进行全局错误处理
问题描述
我在 vuejs 中使用 axios,并且在 axios 调用时遇到全局错误处理问题。我正在尝试如下,它不仅需要用户注销,而且还在 axios 调用后执行代码块。如果发生错误,如何防止执行 axios 调用承诺代码部分。
export default {
created() {
var self = this;
if (self.$route.meta.requiresAuth) {
axios.interceptors.response.use(
function(response) {
return response;
},
function(error) {
if (error.response.status == 401) {
self.$toaster.error("ERROR: Invalid token detected");
self.logout();
}
}
);
}
},
methods: {
logout() {
this.$router.push({ name: "login" });
}
}
}
someFunction() {
var self = this;
axios
.post(
"url/to/api",
{},
{
headers: {
Authorization: "authtoken here"
}
}
)
.then(response => {
alert("success");
otherFunction();
})
.catch(error => {
console.log(error);
});
}
解决方案
您将需要从错误拦截器中引发一个新错误。
axios.interceptors.response.use(
function(response) {
return response;
},
function(error) {
if (error.response.status == 401) {
self.$toaster.error("ERROR: Invalid token detected");
self.logout();
}
throw new Error('Invalid token detected')
}
);
}
推荐阅读
- compiler-errors - 为什么我不能将 main.rs 添加到 crate 的源代码并导入结构?
- python - 使用 Python 输出 YAML:输入中没有列表的格式不正确
- python - Python - 分页循环
- java - 形状文件或 geojson 到数据库
- javascript - 创建新组件时创建要重用的基础组件
- c# - 意外记录
- ionic-framework - Ionic Navigator Launch 不起作用。我点击按钮,没有任何反应
- javascript - Webpack:html和js文件不在同一个文件夹中的项目的output.path、publicPath和chunkFilename选择概念
- javascript - D3:如何在两种颜色之间进行插值?
- c - 如何调试 libsass 库?