0

我正在用 Nuxt 和 Prismic 作为 CMS 建立一个博客。

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

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

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

在 pages 目录中,我有动态链接( _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 上的项目

4

2 回答 2

3

另外我不确定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 文档~

于 2020-09-01T07:26:19.927 回答
2

你能不能只捕获这样的异常:

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');
});

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

于 2020-09-01T01:20:15.317 回答