我理解vuex操作返回承诺,但我还没有找到理想的模式来处理中的错误。我目前的方法是在我的axios插件上使用一个错误拦截器,然后将错误提交给我的vuex存储。
在plugins/axios.js中
export default function({ $axios, store }) {
$axios.onError(error => {
store.dispatch('setError', error.response.data.code);
});
}
在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);
},
};
然后,我将使用错误组件,监视错误状态,并显示是否存在错误。因此,实际上不需要捕获任何错误,无论是在我的操作中还是在发送操作的组件中。然而,我不禁要担心,如果是的糟糕设计,留下了例外,不为呢?如果我通过这个设计来处理错误,我会遇到什么问题?有什么更好的方法吗?
发布于 2018-07-10 00:09:28
我认为您应该在vuex操作中调用API,如果它失败了,就拒绝API调用中的错误承诺。我将避免列出所有的Axios错误,而是在承诺返回错误时处理它,在我看来,这样更容易维护和调试。
例如:
getCartItems: function ({commit}, url) {
return axios.get(url).then(response => {
commit('setCartItems', response.data)
return response
}).catch(error => {
throw error
})
},
发布于 2019-02-09 13:51:14
改进了上面的示例,以避免冗余的承诺包装,并使用异步/等待简化代码:
export const getCartItems = async ({commit}, url) => {
const response = await axios.get(url);
commit('setCartItems', response.data)
return response;
};
https://stackoverflow.com/questions/51235273
复制相似问题