问题描述
我理解vuex操作会返回承诺,但我还没有在vuex中找到理想模式来处理错误。我目前的方法是在我的axios插件上使用错误拦截器,然后将错误提交到我的vuex商店。
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 :
in plugins/axios.js:
export default function({ $axios, store }) {
$axios.onError(error => {
store.dispatch('setError', error.response.data.code);
});
}
商店/ index.js :
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?
推荐答案
我认为你应该在vuex行动中进行API调用,如果它失败了,拒绝来自API调用的错误的promise。我会避免列出所有Axios错误,而是在promise中返回错误时处理错误,在我看来,以这种方式维护和调试会更容易
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
})
},
这篇关于Vue.js:在vuex行动中未被捕获的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!