【问题标题】:Nuxt handle fetch errors from Prismic APINuxt 处理来自 Prismic API 的获取错误
【发布时间】:2020-12-20 02:40:30
【问题描述】:

我正在使用 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上的项目

【问题讨论】:

    标签: error-handling fetch nuxt.js netlify prismic.io


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      我也不确定在页面中使用 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~

      【讨论】:

        猜你喜欢
        • 2018-10-24
        • 2019-08-07
        • 2017-07-05
        • 2020-08-05
        • 2021-08-07
        • 2010-11-11
        • 2017-05-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多