首页 > 解决方案 > 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
    })

我知道我可以通过重新抛出错误来解决这个问题,但这似乎不是最好的方法,因为我一直认为重新抛出错误是不好的做法(尽管在这里它似乎是一个不错的解决方案)我缺少的一些简单的东西?

标签: javascriptvue.jserror-handlingvuejs2vuex

解决方案


这应该没问题,只需进行一项修改。

您可以重新抛出错误以允许父级使用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
  }
}

推荐阅读