问题描述
我了解 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);
});
}
在 store/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 调用的错误.我会避免列出所有 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 操作中未捕获的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!