【问题标题】:VueJS Error handling in VueX store best practicesVueX 商店中的 VueJS 错误处理最佳实践
【发布时间】: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


    【解决方案1】:

    这应该没问题,只需修改一个。

    您可以使用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
      }
    }
    

    【讨论】:

    • 我同意,重新抛出原始异常并没有错,尤其是当第一个 catch 用于记录目的时。
    • 好的,谢谢!有点担心重新抛出,但读过其他似乎表明它可以的文献。
    猜你喜欢
    • 2018-07-17
    • 1970-01-01
    • 2020-03-09
    • 2018-09-12
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多