Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice in Error Handling in Vuejs With Vuex and Axios

Tags:

I am using Vuex + axios, I want to know the best practice in handling errors for vuex + axios. What I am doing now is that when I request using axios and it returns an error, it will be committed in mutation and update my state. What I want to do is, If there's an response error from my request it will return to my component so that I can handle the error much faster.

Like in angular, there's a dependency injection and the response will return to the component.

like image 633
LordGrim Avatar asked Feb 07 '18 06:02

LordGrim


1 Answers

Have your cake and eat it too. Assuming you are already using an interceptor...

axios.interceptors.response.use(function (response) {   return response; }, function (error) {   store.commit('ERROR', error) // just taking some guesses here   return Promise.reject(error) // this is the important part }) 

This will keep the promise rejection going back to the caller so in your component, something like...

axios.whatever(...).then(res => {   // happy days }, err => {   // oh noes! }) 
like image 87
Phil Avatar answered Oct 10 '22 22:10

Phil