Skip to content

Commit baed42c

Browse files
icyJosephijjk
andauthored
fix: Catch hash change errors, and emit a routeChangeError event (#36828)
* fix: Catch hash change errors, and emit a `routeChangeError` event * Add test * update test Co-authored-by: JJ Kasper <[email protected]>
1 parent ef69aca commit baed42c

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

packages/next/shared/lib/router/router.ts

+9-1
Original file line numberDiff line numberDiff line change
@@ -1080,7 +1080,15 @@ export default class Router implements BaseRouter {
10801080
if (scroll) {
10811081
this.scrollToHash(cleanedAs)
10821082
}
1083-
this.set(nextState, this.components[nextState.route], null)
1083+
try {
1084+
await this.set(nextState, this.components[nextState.route], null)
1085+
} catch (err) {
1086+
if (isError(err) && err.cancelled) {
1087+
Router.events.emit('routeChangeError', err, cleanedAs, routeProps)
1088+
}
1089+
throw err
1090+
}
1091+
10841092
Router.events.emit('hashChangeComplete', as, routeProps)
10851093
return true
10861094
}

test/integration/client-navigation/test/index.test.js

+20
Original file line numberDiff line numberDiff line change
@@ -1714,6 +1714,26 @@ describe('Client Navigation', () => {
17141714
expect(value).toBe(false)
17151715
})
17161716

1717+
it('should emit routeChangeError on hash change cancel', async () => {
1718+
const browser = await webdriver(context.appPort, '/')
1719+
1720+
await browser.eval(`(function() {
1721+
window.routeErrors = []
1722+
1723+
window.next.router.events.on('routeChangeError', function (err) {
1724+
window.routeErrors.push(err)
1725+
})
1726+
window.next.router.push('#first')
1727+
window.next.router.push('#second')
1728+
window.next.router.push('#third')
1729+
})()`)
1730+
1731+
await check(async () => {
1732+
const errorCount = await browser.eval('window.routeErrors.length')
1733+
return errorCount > 0 ? 'success' : errorCount
1734+
}, 'success')
1735+
})
1736+
17171737
it('should navigate to paths relative to the current page', async () => {
17181738
const browser = await webdriver(context.appPort, '/nav/relative')
17191739
let page

0 commit comments

Comments
 (0)