pv1
pv1

Reputation: 534

Nuxt 3 - 404 Page Not Found Error and H3Error Page not found

Whenever a user visits a non existing page I get in the logs the following error which I would rather not log for every not found page.

[nuxt] error caught during app initialization H3Error: Page not found: /.git/config at createError (file:///var/www/site1/.output/server/node_modules/h3/dist/index.mjs:128:15) at file:///var/www/site1/.nuxt/dist/server/server.mjs:2154:47 at triggerAfterEach (file:///var/www/site1/.output/server/node_modules/vue-router/dist/vue-router.mjs:3306:13) at file:///var/www/site1/.output/server/node_modules/vue-router/dist/vue-router.mjs:3209:13 at processTicksAndRejections (node:internal/process/task_queues:96:5) at file:///var/www/site1/.nuxt/dist/server/server.mjs:2170:7 at createNuxtAppServer (file:///var/www/site1/.nuxt/dist/server/server.mjs:19902:7) at Object.renderToString (file:///var/www/site1/.output/server/node_modules/vue-bundle-renderer/dist/runtime.mjs:172:19) at file:///var/www/site1/node_modules/nuxt/dist/core/runtime/nitro/renderer.mjs:128:21 at file:///var/www/site1/node_modules/nitropack/dist/runtime/renderer.mjs:12:22 { statusCode: 404, fatal: false, unhandled: false, statusMessage: 'Page not found: /.git/config', __nuxt_error: true }

I tried to create a plugin in plugins folder named errorhandler.ts with this code but its not logging anything

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.config.errorHandler = (error, context) => {
    console.log(error);
    console.log(context);
  };
});

This is an example https://stackblitz.com/edit/nuxt-starter-q2rvlp?file=plugins%2Ferrorhandler.ts.

Can anyone share some thoughts about handling not found error in Nuxt 3 and even creating a custom 404 page?

Thank you in advance!!!

Upvotes: 1

Views: 20252

Answers (4)

LastM4N
LastM4N

Reputation: 2240

In Nuxt 3, you can create a catch-all route ([...path].vue) to handle 404 errors explicitly.

Create the Catch-All Route:

Create a file named [...path].vue in the pages directory:

touch pages/[...path].vue

Add Your Custom 404 Page Content:

<template>
  <div>
    <h1>404</h1>
    <p>
      Oops! The page youโ€™re looking for doesnโ€™t exist.
    </p>
    <nuxt-link to="/">
      Go Back to Home
    </nuxt-link>
  </div>
</template>

<script>
export default {
  name: "NotFoundPage",
};
</script>

How It Works:

The [...path].vue file catches all unmatched routes and serves as your custom 404 page.

Documentation. This is the most native solution for Nuxt 3 that I could find. I hope it helps!

Upvotes: 1

Luuk Verhagen
Luuk Verhagen

Reputation: 360

I encountered the same problem. The 404 error messages were logged even when the 404 errors were handled by an error.vue. After a lot of searching and trying, I created a little Nitro 'plugin' which marks the h3Error as handled before calling the default error handler. This works because an error is only logged if it's marked unhandled or fatal (see source code: https://github.com/nuxt/nuxt/blob/f84df08dbcab675a8419c42cc5c2a5258df37bff/packages/nuxt/src/core/runtime/nitro/error.ts#LL28C36-L28C36)

My code in /server/plugins.error.ts:

import type { H3Error, H3Event } from 'h3'

export default defineNitroPlugin((nitroApp) => {
    const h3OnError = nitroApp.h3App.options.onError;
    nitroApp.h3App.options.onError = (error : Error, event : H3Event) => {
        let h3error : H3Error = error as H3Error;
        
        if(h3error?.statusCode === 404)
        {
            h3error.unhandled = false;
        }

        if(h3OnError !== undefined)
        {
            return h3OnError(error, event);
        }
        return;
    };
})

I hope this helps.

Upvotes: 2

Januar Fonti
Januar Fonti

Reputation: 1

I'm also still playing with this error handling, here is my fetcher on the [id].vue file.

const { id } = useRoute().params

const { data: student, error } = await useMyFetch<IStudentApplicationDetail>(
  `/api/member-student-application/${id}`
)

if (error.value) {
  throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })
}

Here is my error.ts plugins

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.config.errorHandler = (error, context) => {
    console.log('๐Ÿš€ ~ file: error.ts:6 ~ defineNuxtPlugin ~ context:', context)
    console.log('๐Ÿš€ ~ file: error.ts:6 ~ defineNuxtPlugin ~ error:', error)
  }
})

With this error handling, I got the console log on the server side. Here is the full error

๐Ÿš€ ~ file: error.ts:6 ~ defineNuxtPlugin ~ context: {}                                                               23:28:22
๐Ÿš€ ~ file: error.ts:6 ~ defineNuxtPlugin ~ error: H3Error: Page Not Found                                            23:28:22
    at Module.createError (file:///Users/januarfonti/Code/Clearview/asifa/asifa-member-fe/node_modules/h3/dist/index.mjs:128:15)
    at Module.createError (/Users/januarfonti/Code/Clearview/asifa/asifa-member-fe/node_modules/nuxt/dist/app/composables/error.js:37:38)
    at setup (/Users/januarfonti/Code/Clearview/asifa/asifa-member-fe/pages/admin/members/student-applications/view/[id].vue:43:35)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  statusCode: 404,
  fatal: false,
  unhandled: false,
  statusMessage: 'Page Not Found',
  __nuxt_error: true
}

I'm not sure if it's a good error handler since I still got another error instead of only the console.log

Upvotes: 0

Reagan
Reagan

Reputation: 2385

Based on the Error handling documentation,

"You can customize this error page by adding ~/error.vue in the source directory of your application, alongside app.vue. This page has a single prop - error which contains an error for you to handle."

Here is an example https://stackblitz.com/edit/nuxt-starter-q97lbh?file=error.vue

Upvotes: 1

Related Questions