Skip to content

Commit

Permalink
fix: Catch hash change errors, and emit a routeChangeError event (#…
Browse files Browse the repository at this point in the history
…36828)

* fix: Catch hash change errors, and emit a `routeChangeError` event

* Add test

* update test

Co-authored-by: JJ Kasper <jj@jjsweb.site>
  • Loading branch information
icyJoseph and ijjk committed May 22, 2022
1 parent ef69aca commit baed42c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
10 changes: 9 additions & 1 deletion packages/next/shared/lib/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1080,7 +1080,15 @@ export default class Router implements BaseRouter {
if (scroll) {
this.scrollToHash(cleanedAs)
}
this.set(nextState, this.components[nextState.route], null)
try {
await this.set(nextState, this.components[nextState.route], null)
} catch (err) {
if (isError(err) && err.cancelled) {
Router.events.emit('routeChangeError', err, cleanedAs, routeProps)
}
throw err
}

Router.events.emit('hashChangeComplete', as, routeProps)
return true
}
Expand Down
20 changes: 20 additions & 0 deletions test/integration/client-navigation/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1714,6 +1714,26 @@ describe('Client Navigation', () => {
expect(value).toBe(false)
})

it('should emit routeChangeError on hash change cancel', async () => {
const browser = await webdriver(context.appPort, '/')

await browser.eval(`(function() {
window.routeErrors = []
window.next.router.events.on('routeChangeError', function (err) {
window.routeErrors.push(err)
})
window.next.router.push('#first')
window.next.router.push('#second')
window.next.router.push('#third')
})()`)

await check(async () => {
const errorCount = await browser.eval('window.routeErrors.length')
return errorCount > 0 ? 'success' : errorCount
}, 'success')
})

it('should navigate to paths relative to the current page', async () => {
const browser = await webdriver(context.appPort, '/nav/relative')
let page
Expand Down

0 comments on commit baed42c

Please sign in to comment.