fix(nuxt): call app:error in SSR before rendering error page (#20511)

This commit is contained in:
Daniel Roe 2023-04-26 14:36:59 +01:00 committed by GitHub
parent dd0d13d425
commit 197de3ecbb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 13 additions and 7 deletions

View File

@ -41,6 +41,7 @@ This includes:
* running Nuxt plugins
* processing `app:created` and `app:beforeMount` hooks
* rendering your Vue app to HTML (on the server)
* mounting the app (on client-side), though you should handle this case with `onErrorCaptured` or with `vue:error`
* processing the `app:mounted` hook

View File

@ -48,11 +48,12 @@ export function useCookie <T = string | null | undefined> (name: string, _opts?:
}
}
const unhook = nuxtApp.hooks.hookOnce('app:rendered', writeFinalCookieValue)
nuxtApp.hooks.hookOnce('app:redirected', () => {
// don't write cookie subsequently when app:rendered is called
unhook()
const writeAndUnhook = () => {
unhook() // don't write cookie subsequently when app:rendered is called
return writeFinalCookieValue()
})
}
nuxtApp.hooks.hookOnce('app:error', writeAndUnhook)
nuxtApp.hooks.hookOnce('app:redirected', writeAndUnhook)
}
return cookie as CookieRef<T>

View File

@ -244,9 +244,11 @@ export default defineRenderHandler(async (event) => {
writeEarlyHints(event, link)
}
const _rendered = await renderer.renderToString(ssrContext).catch((error) => {
const _rendered = await renderer.renderToString(ssrContext).catch(async (error) => {
// Use explicitly thrown error in preference to subsequent rendering errors
throw (!ssrError && ssrContext.payload?.error) || error
const _err = (!ssrError && ssrContext.payload?.error) || error
await ssrContext.nuxt?.hooks.callHook('app:error', _err)
throw _err
})
await ssrContext.nuxt?.hooks.callHook('app:rendered', { ssrContext })

View File

@ -571,6 +571,7 @@ describe('errors', () => {
it('should render a HTML error page', async () => {
const res = await fetch('/error')
expect(res.headers.get('Set-Cookie')).toBe('some-error=was%20set; Path=/')
expect(await res.text()).toContain('This is a custom error')
})

View File

@ -45,7 +45,7 @@ describe.skipIf(isWindows || process.env.TEST_BUILDER === 'webpack' || process.e
it('default server bundle size', async () => {
stats.server = await analyzeSizes(['**/*.mjs', '!node_modules'], serverDir)
expect(roundToKilobytes(stats.server.totalBytes)).toMatchInlineSnapshot('"67.2k"')
expect(roundToKilobytes(stats.server.totalBytes)).toMatchInlineSnapshot('"67.3k"')
const modules = await analyzeSizes('node_modules/**/*', serverDir)
expect(roundToKilobytes(modules.totalBytes)).toMatchInlineSnapshot('"2657k"')

View File

@ -11,6 +11,7 @@ const { data, error } = await useAsyncData(() => {
}, { server: true })
if (error.value) {
useCookie('some-error').value = 'was set'
throw createError({ statusCode: 422, fatal: true, statusMessage: 'This is a custom error' })
}