Nuxt Fetch Handle Error / Show Error Page

June 12, 2020

Option 1: $fetchState.error

Show error at page component.

<template>
  <div>
    <div v-if="$fetchState.pending">Loading ...</div>
    <div v-else-if="$fetchState.error">Error: {{ $fetchState.error.message }}</div>
    <div>
      {{ title }}
    </div>
  </div>
</template>

<script>
export default {
  async fetch() {
    // const HOST = 'http://localhost:8080' // required for server-side fetch
    // const url = new URL(`/data/test.json`, HOST)
    const url = 'https://jsonplaceholder.typicode.com/posts/1'
    // alternatvely, you could use $axios or $http
    const res = await fetch(url)

    if (res.status != 200) {
       throw new Error('Post not found')
    }

    const data = await res.json()

    this.title = data.title
  },
  data() {
    return {
      title: null
    }
  },
}
</script>

Option 2: $nuxt.error

Show custom error page.

<template>
  <div>
    <div v-if="!$fetchState.pending && !$fetchState.error">
      {{ title }}
    </div>
  </div>
</template>

<script>
export default {
  async fetch() {
    // const HOST = 'http://localhost:8080' // required for server-side fetch
    // const url = new URL(`/data/test.json`, HOST)
    const url = 'https://jsonplaceholder.typicode.com/posts/1'
    // alternatvely, you could use $axios or $http
    const res = await fetch(url)

    if (res.status != 200) {
       this.$nuxt.error({ statusCode: res.status, message: 'Post not found' })
    }

    const data = await res.json()

    this.title = data.title
  },
  data() {
    return {
      title: null
    }
  },
}
</script>
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.