@@ -19,16 +19,11 @@ const errorHandlers: Array<ErrorHandler> = []
19
19
const rejectionHandlers : Array < ErrorHandler > = [ ]
20
20
21
21
if ( 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
29
25
}
30
26
31
- const error = ev ?. error
32
27
if (
33
28
! error ||
34
29
! ( error instanceof Error ) ||
@@ -60,18 +55,39 @@ if (typeof window !== 'undefined') {
60
55
'\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error'
61
56
}
62
57
63
- const e = error
64
58
// Only queue one hydration every time
65
59
if ( isCausedByHydrationFailure ) {
66
60
if ( ! hasHydrationError ) {
67
- errorQueue . push ( e )
61
+ errorQueue . push ( error )
68
62
}
69
63
hasHydrationError = true
70
64
}
71
65
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 )
73
89
}
74
- } )
90
+ }
75
91
window . addEventListener (
76
92
'unhandledrejection' ,
77
93
( ev : WindowEventMap [ 'unhandledrejection' ] ) : void => {
0 commit comments