Vue.js: Uncaught promises in vuex actions

2019-03-31 04:42发布

I understand vuex actions return promises, but I haven't found the ideal pattern to handle errors in vuex. My current approach is to use an error interceptor on my axios plugin, then committing the error to my vuex store.

in plugins/axios.js:

export default function({ $axios, store }) {
    $axios.onError(error => {
        store.dispatch('setError', error.response.data.code);
    });
}

in store/index.js:

export const state = () => ({
    error: null,
});

export const mutations = {
    SET_ERROR(state, payload) {
        state.error = payload;
    },
}

export const actions = {
    setError({ commit }, payload) {
        commit('SET_ERROR', payload);
    },
};

I would then use an error component watching the error state and show if there is an error. Thus there is really no need to catch any errors in either my action or in the component that dispatched the action. However I can't help to worry if it's bad design leaving exceptions uncaught? What issues could I encounter if I handle errors by this design? Suggestions on any better ways to do this?

2条回答
贪生不怕死
2楼-- · 2019-03-31 05:17

I would argue that you should make the API call in the vuex action and if it fails, reject the promise with the error from the API call. I would avoid listing to all Axios errors and instead handle the error when it is returned in the promise, in my opinion, it would be easier to maintain and debug this way vuex usage

For example:

getCartItems: function ({commit}, url) {
    return axios.get(url).then(response => {
      commit('setCartItems', response.data)
      return response
    }).catch(error => {
      throw error
    })
 },
查看更多
狗以群分
3楼-- · 2019-03-31 05:17

Improved above example to avoid redundant promise wrapping and use async/await for simplified code:

export const getCartItems = async ({commit}, url) => {
  const response = await axios.get(url);
  commit('setCartItems', response.data)
  return response;
};
查看更多
登录 后发表回答