Nuxt处理从Prismic API提取错误

问题描述

我正在建立一个以Nuxt to和Prismic为CMS的博客

我的nuxt.config.js看起来像这样:

mode: 'universal',modules: ['@nuxtjs/prismic'],target: 'static',generate: {
    fallback: '404.html',},

使用构建命令“ npm run generate”将项目部署在Netlify上

页面目录中,我具有动态链接(_uid.vue),在其中我使用新的fetch根据路线获取帖子。

async fetch() {
    const post = await this.$prismic.api.getByUID('blog-post',this.$route.params.uid)
    this.post = post
},

一切正常!但是我想处理提取错误显示相应的错误页面。例如,当我们尝试获取的帖子不存在或现在被删除时。我从上面提供的有关访存的链接中进行了尝试,但显示出未定义帖子的错误

async fetch() {
  const post = await await this.$prismic.api.getByUID('blog-post',this.$route.params.uid)
  
  if (post.id === this.$route.params.id) {
      this.post = post
    } else {
      // set status code on server and
      if (process.server) {
        this.$nuxt.context.res.statusCode = 404
      }
      // use throw new Error()
      throw new Error('Post not found')
    }
}

我在GitHub上的项目

解决方法

我也不确定在页面内使用fetch钩是否被视为最佳实践,我认为您应该更喜欢使用asyncData以下模式(或async/await):

export default {
  asyncData({ params,error }) {
    return axios
      .get(`https://my-api/posts/${params.id}`)
      .then(res => {
        return { title: res.data.title }
      })
      .catch(e => {
        error({ statusCode: 404,message: 'Post not found' })
      })
  }
}

来自Nuxt documentation

,

您能否不仅捕获到这样的异常:

try {
  const post = await this.$prismic.api.getByUID('blog-post',this.$route.params.uid);
  if (post.id === this.$route.params.id) {
    this.post = post;
  }
} catch ((error) => {
  // set status code on server and
  if (process.server) {
    this.$nuxt.context.res.statusCode = 404;
  }
  // use throw new Error()
  throw new Error('Post not found');
});

当然,您必须实际检查发生的异常类型。