From 69c281f384bd0cbd91251b9cbfefc5f948a91a65 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Wed, 17 Aug 2022 17:14:00 +0800 Subject: [PATCH] fix(nuxt): fallback to static error page on server error (#6697) Co-authored-by: Pooya Parsa --- packages/nuxt/src/core/runtime/nitro/error.ts | 25 +++++++++++++------ test/basic.test.ts | 1 - 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/packages/nuxt/src/core/runtime/nitro/error.ts b/packages/nuxt/src/core/runtime/nitro/error.ts index e192b2ba06..896c5179fa 100644 --- a/packages/nuxt/src/core/runtime/nitro/error.ts +++ b/packages/nuxt/src/core/runtime/nitro/error.ts @@ -13,7 +13,7 @@ export default async function errorhandler (error: H3Error, statusCode, statusMessage, message, - description: process.env.NODE_ENV === 'development' && statusCode !== 404 + stack: process.dev && statusCode !== 404 ? `
${stack.map(i => `${i.text}`).join('\n')}
` : '', data: error.data @@ -42,12 +42,23 @@ export default async function errorhandler (error: H3Error, return } - // HTML response - const url = withQuery('/__nuxt_error', errorObject) - const html = await $fetch(url).catch((error) => { - console.error('[nitro] Error while generating error response', error) - return errorObject.statusMessage - }) + // HTML response (via SSR) + const isErrorPage = event.req.url?.startsWith('/__nuxt_error') + let html = !isErrorPage ? await $fetch(withQuery('/__nuxt_error', errorObject)).catch(() => null) : null + + // Fallback to static rendered error page + if (!html) { + const { template } = process.dev + // @ts-ignore + ? await import('@nuxt/ui-templates/templates/error-dev.mjs') + // @ts-ignore + : await import('@nuxt/ui-templates/templates/error-500.mjs') + if (process.dev) { + // TODO: Support `message` in template + (errorObject as any).description = errorObject.message + } + html = template(errorObject) + } event.res.setHeader('Content-Type', 'text/html;charset=UTF-8') event.res.end(html) diff --git a/test/basic.test.ts b/test/basic.test.ts index a361730843..cb5a170d13 100644 --- a/test/basic.test.ts +++ b/test/basic.test.ts @@ -181,7 +181,6 @@ describe('errors', () => { const error = await res.json() delete error.stack expect(error).toMatchObject({ - description: process.env.NUXT_TEST_DEV ? expect.stringContaining('
') : '',
       message: 'This is a custom error',
       statusCode: 500,
       statusMessage: 'Internal Server Error',