Sometimes, we want to handle errors in Vue.js with Vuex and Axios.
In this article, we’ll look at how to handle errors in Vue.js with Vuex and Axios.
How to handle errors in Vue.js with Vuex and Axios?
To handle errors in Vue.js with Vuex and Axios, we can add a response interceptor.
For instance, we write
axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
store.commit("ERROR", error);
return Promise.reject(error);
}
);
to call axios.interceptors.response.use
with the error handler in the 2nd argument.
In it, we call store.commit
to put the error data in the Vuex store by committing the ERROR
mutation.
And then we return a rejected promise with the error
as the rejection reason.
Then we can catch any request errors with a catch
block:
try {
await axios.get("...");
} catch (e) {
console.log(e);
}
Conclusion
To handle errors in Vue.js with Vuex and Axios, we can add a response interceptor.