Skip to content

Commit

Permalink
Check for window before adding event listener
Browse files Browse the repository at this point in the history
  • Loading branch information
alexkirsz committed Nov 7, 2022
1 parent dee96bc commit cd81899
Showing 1 changed file with 45 additions and 39 deletions.
Expand Up @@ -31,55 +31,61 @@ const rejectionQueue: Array<Error> = []
const errorHandlers: Array<ErrorHandler> = []
const rejectionHandlers: Array<ErrorHandler> = []

// These event handlers must be added outside of the hook because there is no
// guarantee that the hook will be alive in a mounted component in time to
// when the errors occur.
window.addEventListener('error', (ev: WindowEventMap['error']): void => {
if (isNextRouterError(ev.error)) {
ev.preventDefault()
return
}

RuntimeErrorHandler.hadRuntimeError = true

const error = ev?.error
if (!error || !(error instanceof Error) || typeof error.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-(
return
}

if (isHydrationError(error)) {
error.message += `\n\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error`
}

const e = error
errorQueue.push(e)
for (const handler of errorHandlers) {
handler(e)
}
})
window.addEventListener(
'unhandledrejection',
(ev: WindowEventMap['unhandledrejection']): void => {
if (typeof window !== 'undefined') {
// These event handlers must be added outside of the hook because there is no
// guarantee that the hook will be alive in a mounted component in time to
// when the errors occur.
window.addEventListener('error', (ev: WindowEventMap['error']): void => {
if (isNextRouterError(ev.error)) {
ev.preventDefault()
return
}

RuntimeErrorHandler.hadRuntimeError = true

const reason = ev?.reason
const error = ev?.error
if (
!reason ||
!(reason instanceof Error) ||
typeof reason.stack !== 'string'
!error ||
!(error instanceof Error) ||
typeof error.stack !== 'string'
) {
// A non-error was thrown, we don't have anything to show. :-(
return
}

const e = reason
rejectionQueue.push(e)
for (const handler of rejectionHandlers) {
if (isHydrationError(error)) {
error.message += `\n\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error`
}

const e = error
errorQueue.push(e)
for (const handler of errorHandlers) {
handler(e)
}
}
)
})
window.addEventListener(
'unhandledrejection',
(ev: WindowEventMap['unhandledrejection']): void => {
RuntimeErrorHandler.hadRuntimeError = true

const reason = ev?.reason
if (
!reason ||
!(reason instanceof Error) ||
typeof reason.stack !== 'string'
) {
// A non-error was thrown, we don't have anything to show. :-(
return
}

const e = reason
rejectionQueue.push(e)
for (const handler of rejectionHandlers) {
handler(e)
}
}
)
}

export function useErrorHandler(
handleOnUnhandledError: ErrorHandler,
Expand Down

0 comments on commit cd81899

Please sign in to comment.