msonowal
msonowal

Reputation: 1687

NUXT JS Interceptor for 404 or any errors with error method not working

Version

v5.8.0

Reproduction link

https://github.com/msonowal/nuxt-bug-reproduce-link

Steps to reproduce

add this in plugins dir make file name it axios.js

and add the link in nuxt config plugins array visit any route whose axios calls are 404

axios.js file content below

export default function({ $axios, error }) {
  $axios.onError((responseError) => {
    if (responseError.response.status === 404) {
      error({ statusCode: 404, message: 'Post not found from interceptor' })
    }
  })
}

What is expected ?

show the error response with 404 code as defined in the nuxt app Post not found from interceptor

but

not redirect to 301

What is actually happening?

it is showing default nuxt error

NuxtServerError Request failed with status code 404

This bug report is available on Nuxt community (#c305)

Upvotes: 0

Views: 4809

Answers (2)

atazmin
atazmin

Reputation: 5687

This seem to work for me

_.vue

async asyncData(context) {
  ...
  try {
    const response = await context.$axios(options);
    ...          
  } catch (error) {
    context.error({ statusCode: 404, message: 'Page not found' });
  }
}

error.vue

<template>
  <h1>{{ error.message }}</h1>
</template>

<script>
  export default {
    head() {
      return {
        title: `${this.statusCode} | ${this.message}`,
      }
    },
    props: {
      error: {
        type: Object,
        default: null
      }
    },
    computed: {
      statusCode() {
        return (this.error && this.error.statusCode) || 500;
      },
      message() {
        return this.error.message;
      }
    }
  }
</script>

Upvotes: 2

sid heart
sid heart

Reputation: 1149

this is the way you can handle error 404

asyncData({ $axios, params, error }) {
    return $axios
      .get(`/user/${params.profile}`)
      .then(res => {
        return { user: res.data.data };
      })
      .catch(e => {
        error({ statusCode: 404, message: 'Page not found' });
      });
  },

Upvotes: 0

Related Questions