You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt 2中通过代码重定向至错误页面?

解决Nuxt 2 Vuex Action中触发错误页面的问题

在Nuxt 2里,$error是页面组件的专属方法,Vuex Action的上下文里默认没法直接通过this访问到它,你可以用以下两种方式实现需求:

方案一:在页面fetch中捕获错误并触发错误页面

这种方式更灵活,适合需要在页面层自定义错误处理逻辑的场景:

  1. 修改Vuex Action,把错误向上抛出:
async fetchVotes ({ commit }) {
  try {
    const response = await this.$secured.get('exampleapi.com/votes')
    const merged = jsonApiMerge(response.data.included, response.data.data)
    commit(SET_VOTES_LIST, merged)
  } catch (err) {
    // 抛出错误,交给调用该action的页面fetch处理
    throw err
  }
}
  1. 在页面的fetch方法中捕获错误,调用$error:
async fetch() {
  try {
    await this.fetchVotes() // 调用映射后的Vuex action
  } catch (err) {
    // 处理Axios错误结构,兼容网络错误等无response的情况
    const statusCode = err.response?.status || 500
    const message = err.message || '请求失败,请稍后重试'
    this.$error({ statusCode, message })
  }
}

方案二:直接在Vuex Action中通过Nuxt实例触发错误页面

如果所有调用该action的页面都需要统一的错误处理,可以直接在Action中通过Nuxt实例触发错误页面:

修改Action的catch代码块:

catch (err) {
  // 通过store实例的$nuxt属性访问Nuxt app实例
  this.$nuxt.error({
    statusCode: err.response?.status || 500,
    message: err.message || '获取投票数据失败'
  })
}

注意:Axios错误需要区分情况,当请求未到达服务器时(如网络错误),err.response会不存在,所以要给statusCode设置默认值。

内容的提问来源于stack exchange,提问作者zcserei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 20:23:22