0
votes

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)
2
axios doesn't handle nuxt routing errors - Lawrence Cherone
for best practice catch the error and return to error page - sid heart
@sidheart Thats what I have custom error page setup to handle these errors form nuxt so I want to automate the axios fails to use that same view and make the core SOLID and DRY - msonowal
@msonowal before i thought this plugins style will works fine. but no i was wrong i think this is bug or this feature not added yet. be clear check my answer how i managed 404 error - sid heart
Add throw responseError after if ? - Fahmi

2 Answers

1
votes

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>
0
votes

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