我在vuejs中使用axios,并且在axios调用时遇到全局错误处理问题。我正在尝试如下,它不仅需要用户注销,而且还在axios调用后执行代码块。如果发生错误,如何阻止执行axios调用promise代码段。
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')
}
);
}