Nuxt Fetch Handle Error / Show Error Page

Jun 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>

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.