fix(nuxt): show error page after fatal abortNavigation (#21047)

This commit is contained in:
Alexander 2023-05-26 00:29:22 +06:00 committed by GitHub
parent 4e6369cefa
commit e50cabfed1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 4 deletions

View File

@ -6,7 +6,7 @@ import { hasProtocol, joinURL, parseURL } from 'ufo'
import { useNuxtApp, useRuntimeConfig } from '../nuxt' import { useNuxtApp, useRuntimeConfig } from '../nuxt'
import type { NuxtError } from './error' import type { NuxtError } from './error'
import { createError } from './error' import { createError, showError } from './error'
import { useState } from './state' import { useState } from './state'
import type { PageMeta } from '#app' import type { PageMeta } from '#app'
@ -155,10 +155,16 @@ export const abortNavigation = (err?: string | Partial<NuxtError>) => {
if (process.dev && !isProcessingMiddleware()) { if (process.dev && !isProcessingMiddleware()) {
throw new Error('abortNavigation() is only usable inside a route middleware handler.') throw new Error('abortNavigation() is only usable inside a route middleware handler.')
} }
if (err) {
throw createError(err) if (!err) { return false }
err = createError(err)
if (err.fatal) {
useNuxtApp().runWithContext(() => showError(err as NuxtError))
} }
return false
throw err
} }
export const setPageLayout = (layout: string) => { export const setPageLayout = (layout: string) => {

View File

@ -710,6 +710,14 @@ describe('middlewares', () => {
expect(res.status).toEqual(401) expect(res.status).toEqual(401)
}) })
it('should allow aborting navigation fatally on client-side', async () => {
const html = await $fetch('/middleware-abort')
expect(html).not.toContain('This is the error page')
const page = await createPage('/middleware-abort')
await page.waitForLoadState('networkidle')
expect(await page.innerHTML('body')).toContain('This is the error page')
})
it('should inject auth', async () => { it('should inject auth', async () => {
const html = await $fetch('/auth') const html = await $fetch('/auth')

View File

@ -0,0 +1,18 @@
<script setup lang="ts">
definePageMeta({
middleware: () => {
if (process.server || useNuxtApp().isHydrating) { return }
return abortNavigation({
fatal: true
})
}
})
const router = useRouter()
onNuxtReady(() => router.push({ path: '/middleware-abort', force: true }))
</script>
<template>
<div>
<!-- -->
</div>
</template>