Unverified Commit db04cc57 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Make sure to handle rejection when prefetching pages (#10579)

* Make sure to handle rejection when prefetching pages

* Update comment

* Make sure to show prefetch error in development still
parent c66f2f75
...@@ -209,7 +209,15 @@ class Link extends Component<LinkProps> { ...@@ -209,7 +209,15 @@ class Link extends Component<LinkProps> {
if (!this.p || typeof window === 'undefined') return if (!this.p || typeof window === 'undefined') return
// Prefetch the JSON page if asked (only in the client) // Prefetch the JSON page if asked (only in the client)
const [href, asPath] = this.getPaths() const [href, asPath] = this.getPaths()
Router.prefetch(href, asPath, options) // We need to handle a prefetch error here since we may be
// loading with priority which can reject but we don't
// want to force navigation since this is only a prefetch
Router.prefetch(href, asPath, options).catch(err => {
if (process.env.NODE_ENV !== 'production') {
// rethrow to show invalid URL errors
throw err
}
})
prefetched[href] = true prefetched[href] = true
} }
......
import Link from 'next/link'
export default () => (
<>
<Link href="/something-invalid-oops">
<a id="invalid-link">I'm broken...</a>
</Link>
</>
)
...@@ -163,6 +163,21 @@ describe('Prefetching Links in viewport', () => { ...@@ -163,6 +163,21 @@ describe('Prefetching Links in viewport', () => {
} }
}) })
it('should not have unhandledRejection when failing to prefetch on link', async () => {
const browser = await webdriver(appPort, '/')
await browser.eval(`(function() {
window.addEventListener('unhandledrejection', function (err) {
window.hadUnhandledReject = true;
})
window.next.router.push('/invalid-prefetch');
})()`)
expect(await browser.eval('window.hadUnhandledReject')).toBeFalsy()
await browser.elementByCss('#invalid-link').moveTo()
expect(await browser.eval('window.hadUnhandledReject')).toBeFalsy()
})
it('should not prefetch when prefetch is explicitly set to false', async () => { it('should not prefetch when prefetch is explicitly set to false', async () => {
const browser = await webdriver(appPort, '/opt-out') const browser = await webdriver(appPort, '/opt-out')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment