Nuxt handle fetch errors from Prismic API

3.7k views Asked by At

I'm building a blog with Nuxt to and Prismic as CMS.

my nuxt.config.js looks like this:

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

Project is deployed on Netlify with build command "npm run generate"

In pages directory I have dynamic links ( _uid.vue ) where I use the new fetch to get the post according to route.

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

This all works! However I want to handle fetch errors and display correspond error page. For example when the post we try to fetch does not exist or now is deleted. I tried as they show from the link I provide above about fetch, but I get error that post is undefined.

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

My project on GitHub

2

There are 2 answers

0
Cyclonecode On

Could you not just catch any exceptions like this:

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

Of course you would have to actually check the kind of exception occurred.

0
lihbr On

Also I'm not sure using the fetch hook inside a page is considered a best practice, I think you should prefer asyncData with the following pattern (or async/await one):

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

From Nuxt documentation~