【问题标题】:NUXT - asyncData and vue Actions error handlingNUXT - asyncData 和 vue Actions 错误处理
【发布时间】:2021-04-09 04:54:21
【问题描述】:

我在http://mywebsite.com/[category that doesn't exist] 的路线上(根据下面的代码)会引发错误。但是,我似乎无法进入 asyncData 中的 catch 块。

async asyncData({ params, store }) {
  try { 
    await store.dispatch('categories/GET_CATEGORIES')
    await store.dispatch('products/GET_products', params.category)
  } catch(e) {
    console.log(e) // doesn't console log anything
  }
}

Vuex 动作:

async GET_PRODUCTS({commit}, category) {
  try {
    let url
    if (!category) {
      url = 'some url'
    } else {
      url = 'some other url'
    }

    const response = await this.$axios.$get(url)

    if (!response.length) throw new Error()
    
    commit('some mutation', response.data)
  } catch(e) {
    console.log(e)
  }
}

当我抛出错误时,它不应该也调用asyncData中的catch块吗?我之所以要这样做是因为如果操作出现错误,我想使用路由器导航到主页。

我在 Vuex 中发现的关于路由的文档很少(不推荐?)。但是,asyncData 具有 context 对象,其中包括 router

【问题讨论】:

  • 我个人不会认为这是一种不好的做法,尤其是因为您在其他地方也遇到了这种情况。如果您对此感到担忧,您仍然可以从您的操作中重新抛出错误。

标签: javascript vue.js nuxt.js


【解决方案1】:

您的操作已经在捕捉错误并吞下它们。

要允许调用者处理错误,您可以在操作中重新抛出错误:

async GET_PRODUCTS({commit}, category) {
  try {
    //...
    const response = await this.$axios.$get(url)

  } catch(e) {
    // do something with `e` here...

    // then rethrow error
    throw e
  }
}

【讨论】:

    猜你喜欢
    • 2019-05-03
    • 2020-12-27
    • 2022-11-11
    • 2021-10-19
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2021-07-18
    • 2021-05-19
    相关资源
    最近更新 更多