Reputation: 63
I am using axios in vuejs and have a trouble with global error handling while axios call. I'm trying as follow and it not only takes user logout but also executes the code block after the axios call. How can I prevent the execution of the axios call promise code section if error occurs.
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);
});
}
Upvotes: 3
Views: 6610
Reputation: 842
You will need to raise a new error from the error interceptor.
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')
}
);
}
Upvotes: 1