@@ -19,16 +19,11 @@ const errorHandlers: Array<ErrorHandler> = []
1919const rejectionHandlers : Array < ErrorHandler > = [ ]
2020
2121if ( typeof window !== 'undefined' ) {
22- // These event handlers must be added outside of the hook because there is no
23- // guarantee that the hook will be alive in a mounted component in time to
24- // when the errors occur.
25- window . addEventListener ( 'error' , ( ev : WindowEventMap [ 'error' ] ) : void => {
26- if ( isNextRouterError ( ev . error ) ) {
27- ev . preventDefault ( )
28- return
22+ function handleError ( error : unknown ) {
23+ if ( isNextRouterError ( error ) ) {
24+ return false
2925 }
3026
31- const error = ev ?. error
3227 if (
3328 ! error ||
3429 ! ( error instanceof Error ) ||
@@ -60,18 +55,39 @@ if (typeof window !== 'undefined') {
6055 '\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error'
6156 }
6257
63- const e = error
6458 // Only queue one hydration every time
6559 if ( isCausedByHydrationFailure ) {
6660 if ( ! hasHydrationError ) {
67- errorQueue . push ( e )
61+ errorQueue . push ( error )
6862 }
6963 hasHydrationError = true
7064 }
7165 for ( const handler of errorHandlers ) {
72- handler ( e )
66+ handler ( error )
67+ }
68+ }
69+ // These event handlers must be added outside of the hook because there is no
70+ // guarantee that the hook will be alive in a mounted component in time to
71+ // when the errors occur.
72+ // uncaught errors go through reportError
73+ window . addEventListener (
74+ 'error' ,
75+ ( event : WindowEventMap [ 'error' ] ) : void | boolean => {
76+ if ( handleError ( event . error ) === false ) {
77+ event . preventDefault ( )
78+ return false
79+ }
80+ }
81+ )
82+ // caught errors go through console.error
83+ const origConsoleError = window . console . error
84+ window . console . error = ( ...args ) => {
85+ // See https://github.com/facebook/react/blob/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78
86+ const error = process . env . NODE_ENV !== 'production' ? args [ 1 ] : args [ 0 ]
87+ if ( handleError ( error ) !== false ) {
88+ origConsoleError . apply ( window . console , args )
7389 }
74- } )
90+ }
7591 window . addEventListener (
7692 'unhandledrejection' ,
7793 ( ev : WindowEventMap [ 'unhandledrejection' ] ) : void => {
0 commit comments