javascript - VueX 商店中的 VueJS 错误处理最佳实践
问题描述
我在处理 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
})
我知道我可以通过重新抛出错误来解决这个问题,但这似乎不是最好的方法,因为我一直认为重新抛出错误是不好的做法(尽管在这里它似乎是一个不错的解决方案)我缺少的一些简单的东西?
解决方案
这应该没问题,只需进行一项修改。
您可以重新抛出错误以允许父级使用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
}
}
推荐阅读
- amazon-web-services - 从 Lambda 到 Aurora 数据库的连接失败
- java - 在所有子项目中的所有测试之前在子项目中运行 checkstyles
- ansible - 将“带有 vars 模板”的 ansible yml 文件转换为“不带模板”的 yml 文件
- android - 在 RxJava2 中创建去抖动器
- c# - 如何将 SQL 多表查询转换为 Linq
- c# - 在 .Net Framework 中使用最新版本的 System.Net.Http
- python - 如何在 tensorflow 或 pytorch 中使用自定义权重初始化创建自定义神经网络
- spring - 如何在 Spring 中注册休眠拦截器
- wordpress - 将博客从博主迁移到 wordpress 时出现“已弃用”错误
- html - 如何正确居中对齐两个相邻框的内容以 2:1 的比例拆分