【发布时间】:2020-10-12 17:17:41
【问题描述】:
我在处理 Vue 中的错误的方式上遇到了一些问题。目前我在 VueX 中使用 try/catch 块来进行一些异步调用。 catch 块处理将错误添加到全局 toast。这工作得很好。
async add({ dispatch }, form) {
try {
await firebase.add(form)
dispatch('getUpdatedList')
} catch (error) {
// Use the global error handle to handle the error
dispatch('error', error)
}
},
error ({ dispatch, commit }, errorMessage) {
console.log(errorMessage)
commit('ERROR', errorMessage)
}
// Add the Errors here
ERROR (state, val) {
state.errors = [val, ...state.errors]
},
我遇到的问题是:当该错误在块中被捕获时,它不允许错误传播到组件,因此我无法按照我想要的方式处理组件中的错误。例如,如果客户端提交了一个表单,但不知何故失败了,那么 promise 的 then 块仍然会执行。所以我不能重置表单,或者停止重定向,或者在客户端做一些 UI 整理。
this.$store
.dispatch('add', this.data)
.then(() => {
//This gets hit no matter what the result
this.showSuccess = true
})
.catch(() => {
// More UI stuff
//Can only hit this when rethrowing the error
this.showLoading = false
this.showRegisterButton = true
})
我知道我可以通过重新抛出错误来解决这个问题,但这似乎不是最好的方法,因为我一直认为重新抛出错误是不好的做法(尽管在这里它似乎是一个不错的解决方案) 有什么我缺少的简单的东西吗?
【问题讨论】:
标签: javascript vue.js error-handling vuejs2 vuex