我了解 vuex actions 返回承诺,但我还没有找到处理错误的理想模式在 vuex 中。我当前的方法是在我的 axios 插件上使用错误拦截器,然后将错误提交到我的 vuex 存储。
in 插件/axios.js:
export default function({ $axios, store }) {
$axios.onError(error => {
store.dispatch('setError', error.response.data.code);
});
}
in 商店/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 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
例如:
getCartItems: function ({commit}, url) {
return axios.get(url).then(response => {
commit('setCartItems', response.data)
return response
}).catch(error => {
throw error
})
},
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)