From: Eduardo San Martin Morote Date: Sun, 27 Sep 2020 12:30:47 +0000 (+0200) Subject: feat: print errors from lazy loading X-Git-Tag: v4.0.0-beta.13~21 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=f6db91aaf496b85c80e74727575cc1c2b1d06282;p=thirdparty%2Fvuejs%2Frouter.git feat: print errors from lazy loading Close #497 --- diff --git a/__tests__/lazyLoading.spec.ts b/__tests__/lazyLoading.spec.ts index f28f2cc8..62a4c3b9 100644 --- a/__tests__/lazyLoading.spec.ts +++ b/__tests__/lazyLoading.spec.ts @@ -4,6 +4,7 @@ import { RouterOptions } from '../src/router' import { RouteComponent } from '../src/types' import { ticks } from './utils' import { FunctionalComponent, h } from 'vue' +import { mockWarn } from 'jest-mock-warn' function newRouter(options: Partial = {}) { let history = createMemoryHistory() @@ -24,6 +25,7 @@ function createLazyComponent() { } describe('Lazy Loading', () => { + mockWarn() it('works', async () => { const { component, resolve } = createLazyComponent() const { router } = newRouter({ @@ -240,6 +242,26 @@ describe('Lazy Loading', () => { expect(spy).toHaveBeenCalledTimes(1) }) + it('prints the error when lazy load fails', async () => { + const { component, reject } = createLazyComponent() + const { router } = newRouter({ + routes: [{ path: '/foo', component }], + }) + + const spy = jest.fn() + + reject(new Error('fail')) + await router.push('/foo').catch(spy) + + expect(spy).toHaveBeenCalled() + expect('fail').toHaveBeenWarned() + + expect(router.currentRoute.value).toMatchObject({ + path: '/', + matched: [], + }) + }) + it('aborts the navigation if async fails', async () => { const { component, reject } = createLazyComponent() const { router } = newRouter({ diff --git a/src/navigationGuards.ts b/src/navigationGuards.ts index 90fd35fe..0ffb9e08 100644 --- a/src/navigationGuards.ts +++ b/src/navigationGuards.ts @@ -245,9 +245,9 @@ export function extractComponentsGuards( guard && guards.push(guardToPromiseFn(guard, to, from, record, name)) } else { // start requesting the chunk already - let componentPromise: Promise = (rawComponent as Lazy< - RouteComponent - >)() + let componentPromise: Promise< + RouteComponent | null | undefined | void + > = (rawComponent as Lazy)() if (__DEV__ && !('catch' in componentPromise)) { warn( @@ -255,7 +255,10 @@ export function extractComponentsGuards( ) componentPromise = Promise.resolve(componentPromise as RouteComponent) } else { - componentPromise = componentPromise.catch(() => null) + // display the error if any + componentPromise = componentPromise.catch( + __DEV__ ? err => err && warn(err) : console.error + ) } guards.push(() => @@ -263,7 +266,7 @@ export function extractComponentsGuards( if (!resolved) return Promise.reject( new Error( - `Couldn't resolve component "${name}" for the following record with path "${record.path}"` + `Couldn't resolve component "${name}" at "${record.path}"` ) ) const resolvedComponent = isESModule(resolved)