苦苦挣扎以设置vuex的错误处理。似乎有很多方法可以做到这一点,并且关于正确的错误处理的文档很少。尽管尚未找到令人满意的解决方案,但我一直在尝试四种替代方案。
备选方案1- 捕获和处理组件上的错误
在 pages / login.vue中:
export default {
methods: {
onLogin() {
this.$store.dispatch('auth/login', {
email: this.email,
password: this.password,
}).then(() => {
this.$router.push('/home');
}).catch((error) {
// handle error in component
});
},
},
}
在 store / auth.js中:
export const actions = {
login({ commit }, { email, password }) {
return this.$axios.post('/api/login', {
email,
password,
}).then((res) => {
doSomething(res);
});
},
}
优点
- 嗯
缺点
- 错误未处理并存储在vuex中。
- 在组件方法中引入了许多样板代码。
备选方案2- vuex中的捕获和处理错误
在 pages / login.vue中:
export default {
methods: {
onLogin() {
this.$store.dispatch('auth/login', {
email: this.email,
password: this.password,
}).then(() => {
this.$router.push('/home');
});
},
},
}
在 store / auth.js中:
export const actions = {
login({ commit }, { email, password }) {
return this.$axios.post('/api/login', {
email,
password,
}).then((res) => {
doSomething(res);
}).catch((error) => {
// store error in application state
commit('SET_ERROR', error);
});
},
}
优点
- vuex可从任何组件访问错误对象
- 可以在布局中使用反应性错误组件,当错误状态更改时会显示出来。
缺点
- 我不确定是否有办法跟踪错误的来源以及从哪个组件抛出错误。
Alternative 3 - Catching errors using axios interceptors
in plugins/axios.js:
export default function({ $axios, store }) {
$axios.onError(error => {
store.dispatch('setError', error);
});
}
in pages/login.vue:
export default {
methods: {
onLogin() {
this.$store.dispatch('auth/login', {
email: this.email,
password: this.password,
}).then(() => {
this.$router.push('/home');
});
},
},
}
in store/auth.js:
export const actions = {
login({ commit }, { email, password }) {
return this.$axios.post('/api/login', {
email,
password,
}).then((res) => {
doSomething(res);
});
},
}
PROS
- Global error handling
- No need to catch errors in either vuex or component
- No boiler-plate code
CONS
- All exceptions are unhandled, meaning non-axios errors are uncaught.
Alternative 4 - Custom error plugin
I've been experimenting in implementing a custom plugin that catches all exceptions, but I'm not succeeding in making it work.
in plugins/catch.js:
export default (ctx, inject) => {
const catchPlugin = function (func) {
return async function (args) {
try {
await func(args)
} catch (e) {
return console.error(e)
}
}
};
ctx.$catch = catchPlugin;
inject('catch', catchPlugin);
}
in pages/login.vue:
export default {
methods: {
onLogin: this.$catch(async function () {
await this.$store.dispatch('auth/login', { email: this.email, password: this.password });
this.$router.push('/home');
}),
},
}
PROS
- No boilerplate.
- All errors caught in plugin.
CONS
- I cannot make it work. :(
我的印象是,缺少有关vue / nuxt中错误处理的文档。有人可以选择第四个替代方法吗?这样理想吗?还有其他选择吗?什么是常规?
感谢您的时间!