fix(vue-app): handle server-side routing errors (#7801)

This commit is contained in:
Matthieu Sieben 2020-08-04 11:29:23 +02:00 committed by GitHub
parent f130901ab1
commit 128c9743c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 48 additions and 2 deletions

View File

@ -246,9 +246,13 @@ async function createApp(ssrContext, config = {}) {
// If server-side, wait for async component to be resolved first
if (process.server && ssrContext && ssrContext.url) {
await new Promise((resolve, reject) => {
router.push(ssrContext.url, resolve, () => {
router.push(ssrContext.url, resolve, (err) => {
// https://github.com/vuejs/vue-router/blob/v3.3.4/src/history/errors.js
if (!err._isRouter) return reject(err)
if (err.type !== 1 /* NavigationFailureType.redirected */) return resolve()
// navigated to a different route in router guard
const unregister = router.afterEach(async (to, from, next) => {
const unregister = router.afterEach(async (to, from) => {
ssrContext.url = to.fullPath
app.context.route = await getRouteData(to)
app.context.params = to.params || {}

View File

@ -350,6 +350,27 @@ describe('basic ssr', () => {
expect(html.includes('Router Guard')).toBe(false)
})
test('/router-guard-error', async () => {
const { html, error } = await nuxt.server.renderRoute('/router-guard-error')
expect(error).toBe(null)
expect(html.includes('Page content')).toBe(false)
})
test('/router-guard-error?error=zepe', async () => {
const { html, error } = await nuxt.server.renderRoute('/router-guard-error?error=zepe')
expect(html.includes('Page content')).toBe(false)
expect(html).toContain('zepe')
expect(error.message).toContain('zepe')
expect(error.statusCode).toBe(500)
})
test('/router-guard-error?throw=ezae', async () => {
await expect(nuxt.server.renderRoute('/router-guard-error?throw=ezae'))
.rejects.toMatchObject({ message: 'ezae' })
})
test('/jsx', async () => {
const { html } = await nuxt.server.renderRoute('/jsx')
expect(html).toContain('<h1>JSX Page</h1>')

View File

@ -70,6 +70,7 @@ export default {
plugins: [
'~/plugins/vuex-module',
'~/plugins/dir-plugin',
'~/plugins/router-guard',
'~/plugins/inject'
],
serverMiddleware: [

View File

@ -0,0 +1,3 @@
<template>
<div>Page content</div>
</template>

View File

@ -0,0 +1,17 @@
export default function ({ app, error }) {
app.router.beforeEach((to, from, next) => {
if (to.path !== '/router-guard-error') {
return next()
}
if (to.query.error) {
error(new Error(to.query.error))
}
if (to.query.throw) {
next(new Error(to.query.throw))
} else {
next(false)
}
})
}