gpt4 book ai didi

javascript - VueX 商店中的 VueJS 错误处理最佳实践

转载 作者:行者123 更新时间:2023-12-03 07:48:26 25 4
gpt4 key购买 nike

我在处理 Vue 中的错误时遇到了一些问题。目前我在 VueX 中使用 try/catch block 来进行一些异步调用。 catch block 处理将错误添加到全局 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]
},
我遇到的问题是:当 block 中捕获该错误时,它不允许错误传播到组件,因此我无法按照我想要的方式处理组件中的错误。例如,如果客户端提交了一个表单,但不知何故失败了,那么 promise 的 then block 仍然会执行。所以我不能重置表单,或者停止重定向,或者在客户端上做一些 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
})
我知道我可以通过重新抛出错误来解决这个问题,但这似乎不是最好的前进方式,因为我一直认为重新抛出错误是不好的做法(尽管在这里它似乎是一个不错的解决方案)我缺少的一些简单的东西?

最佳答案

这应该没问题,只需进行一项修改。
您可以使用 throw error 重新抛出错误以允许父级捕获。

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)
// throw the handled error for another handler to catch
throw error
}
}

关于javascript - VueX 商店中的 VueJS 错误处理最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64322418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com