feat(nuxt): add path to error.data when throwing 404 errors (#24674)

This commit is contained in:
Alexander Lichter 2023-12-11 21:30:59 +01:00 committed by GitHub
parent 10c69aa74e
commit 70dea8b83c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 20 additions and 3 deletions

View File

@ -246,7 +246,10 @@ export default defineNuxtPlugin<{ route: Route, router: Router }>({
if (result === false || result instanceof Error) {
const error = result || createError({
statusCode: 404,
statusMessage: `Page Not Found: ${initialURL}`
statusMessage: `Page Not Found: ${initialURL}`,
data: {
path: initialURL
}
})
delete nuxtApp._processingMiddleware
return nuxtApp.runWithContext(() => showError(error))

View File

@ -209,7 +209,10 @@ const plugin: Plugin<{ router: Router }> = defineNuxtPlugin({
await nuxtApp.runWithContext(() => showError(createError({
statusCode: 404,
fatal: false,
statusMessage: `Page not found: ${to.fullPath}`
statusMessage: `Page not found: ${to.fullPath}`,
data: {
path: to.fullPath
}
})))
} else if (import.meta.server && to.redirectedFrom && to.fullPath !== initialURL) {
await nuxtApp.runWithContext(() => navigateTo(to.fullPath || '/'))

View File

@ -15,9 +15,13 @@ export default defineNuxtRouteMiddleware(async (to) => {
if (import.meta.server) {
return result
}
const error = createError({
statusCode: 404,
statusMessage: `Page Not Found: ${to.fullPath}`
statusMessage: `Page Not Found: ${to.fullPath}`,
data: {
path: to.fullPath
}
})
const unsub = router.beforeResolve((final) => {
unsub()

View File

@ -155,6 +155,7 @@ describe('pages', () => {
await page.getByText('should throw a 404 error').click()
expect(await page.getByRole('heading').textContent()).toMatchInlineSnapshot('"Page Not Found: /forbidden"')
expect(await page.getByTestId('path').textContent()).toMatchInlineSnapshot('" Path: /forbidden"')
await gotoPath(page, '/navigate-to-forbidden')
await page.getByText('should be caught by catchall').click()

View File

@ -3,6 +3,12 @@
<div>
<h1>{{ error?.message }}</h1>
This is the error page 😱
<div
v-if="error?.data?.path"
data-testid="path"
>
Path: {{ error.data.path }}
</div>
</div>
</div>
</template>