[Vuejs]-Vue/Nuxt.js: How to handle 404 on nested routes (nuxt-child)

0👍

I think you are looking for error function from context

  async asynData({ params, store, error }) {
    try {
      await axioscall here
    } catch (e) {
      error({ statusCode: 404, message: 'Page not found' })
    }
  },

0👍

Not sure if it is related, I had redirect to error page working in top level pages directory (pages/_.vue), something like this:

  async asyncData(context) {
    ...
    try {
      const response = await context.$axios(options);

      return {
        isPostLoaded: true,
        loadedPost: response.data.data.postBy
      }
    } catch (error) {
      context.error({ statusCode: 404, message: 'Page not found' });
    }
}

but it didn’t work in nested directory in pages (pages/posts/_slug/index.vue)
adding this seem to have helped, I checked if response data was available (might not be the best way but seem to work)

if (response.data.data.postBy === null) {
  throw new Error();
}

async asyncData(context) {
...
    try {
      const response = await context.$axios(options);
    
      if (response.data.data.postBy === null) {
        throw new Error();
      }
    
      return {
        isPostLoaded: true,
        loadedPost: response.data.data.postBy
      }
    } catch (error) {
      context.error({ statusCode: 404, message: 'Page not found' });
    }
}

Leave a comment