-
Notifications
You must be signed in to change notification settings - Fork 28.2k
/
Copy pathuse-error-handler.ts
183 lines (161 loc) · 5.5 KB
/
use-error-handler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import { useCallback, useEffect } from 'react'
import { attachHydrationErrorState } from './attach-hydration-error-state'
import { isNextRouterError } from '../is-next-router-error'
import { storeHydrationErrorStateFromConsoleArgs } from './hydration-error-info'
import { formatConsoleArgs, parseConsoleArgs } from '../../lib/console'
import isError from '../../../lib/is-error'
import { createConsoleError } from './console-error'
import { enqueueConsecutiveDedupedError } from './enqueue-client-error'
import { getReactStitchedError } from '../errors/stitched-error'
import {
ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION,
type useErrorOverlayReducer,
} from '../react-dev-overlay/shared'
import { parseStack } from '../react-dev-overlay/utils/parse-stack'
import { parseComponentStack } from '../react-dev-overlay/utils/parse-component-stack'
const queueMicroTask =
globalThis.queueMicrotask || ((cb: () => void) => Promise.resolve().then(cb))
export type ErrorHandler = (error: Error) => void
const errorQueue: Array<Error> = []
const errorHandlers: Array<ErrorHandler> = []
const rejectionQueue: Array<Error> = []
const rejectionHandlers: Array<ErrorHandler> = []
export function handleConsoleError(
originError: unknown,
consoleErrorArgs: any[]
) {
let error: Error
const { environmentName } = parseConsoleArgs(consoleErrorArgs)
if (isError(originError)) {
error = createConsoleError(originError, environmentName)
} else {
error = createConsoleError(
formatConsoleArgs(consoleErrorArgs),
environmentName
)
}
error = getReactStitchedError(error)
storeHydrationErrorStateFromConsoleArgs(...consoleErrorArgs)
attachHydrationErrorState(error)
enqueueConsecutiveDedupedError(errorQueue, error)
for (const handler of errorHandlers) {
// Delayed the error being passed to React Dev Overlay,
// avoid the state being synchronously updated in the component.
queueMicroTask(() => {
handler(error)
})
}
}
export function handleClientError(originError: unknown) {
let error: Error
if (isError(originError)) {
error = originError
} else {
// If it's not an error, format the args into an error
const formattedErrorMessage = originError + ''
error = new Error(formattedErrorMessage)
}
error = getReactStitchedError(error)
attachHydrationErrorState(error)
enqueueConsecutiveDedupedError(errorQueue, error)
for (const handler of errorHandlers) {
// Delayed the error being passed to React Dev Overlay,
// avoid the state being synchronously updated in the component.
queueMicroTask(() => {
handler(error)
})
}
}
export function useErrorHandlers(
dispatch: ReturnType<typeof useErrorOverlayReducer>[1]
): void {
const handleOnUnhandledError = useCallback(
(error: Error): void => {
// Component stack is added to the error in use-error-handler in case there was a hydration error
const componentStackTrace = (error as any)._componentStack
dispatch({
type: ACTION_UNHANDLED_ERROR,
reason: error,
frames: parseStack(error.stack || ''),
componentStackFrames:
typeof componentStackTrace === 'string'
? parseComponentStack(componentStackTrace)
: undefined,
})
},
[dispatch]
)
const handleOnUnhandledRejection = useCallback(
(reason: Error): void => {
const stitchedError = getReactStitchedError(reason)
dispatch({
type: ACTION_UNHANDLED_REJECTION,
reason: stitchedError,
frames: parseStack(stitchedError.stack || ''),
})
},
[dispatch]
)
useErrorHandler(handleOnUnhandledError, handleOnUnhandledRejection)
}
function useErrorHandler(
handleOnUnhandledError: ErrorHandler,
handleOnUnhandledRejection: ErrorHandler
) {
useEffect(() => {
// Handle queued errors.
errorQueue.forEach(handleOnUnhandledError)
rejectionQueue.forEach(handleOnUnhandledRejection)
// Listen to new errors.
errorHandlers.push(handleOnUnhandledError)
rejectionHandlers.push(handleOnUnhandledRejection)
return () => {
// Remove listeners.
errorHandlers.splice(errorHandlers.indexOf(handleOnUnhandledError), 1)
rejectionHandlers.splice(
rejectionHandlers.indexOf(handleOnUnhandledRejection),
1
)
// Reset error queues.
errorQueue.splice(0, errorQueue.length)
rejectionQueue.splice(0, rejectionQueue.length)
}
}, [handleOnUnhandledError, handleOnUnhandledRejection])
}
function onUnhandledError(event: WindowEventMap['error']): void | boolean {
if (isNextRouterError(event.error)) {
event.preventDefault()
return false
}
// When there's an error property present, we log the error to error overlay.
// Otherwise we don't do anything as it's not logging in the console either.
if (event.error) {
handleClientError(event.error)
}
}
function onUnhandledRejection(ev: WindowEventMap['unhandledrejection']): void {
const reason = ev?.reason
if (isNextRouterError(reason)) {
ev.preventDefault()
return
}
let error = reason
if (error && !isError(error)) {
error = new Error(error + '')
}
rejectionQueue.push(error)
for (const handler of rejectionHandlers) {
handler(error)
}
}
export function handleGlobalErrors() {
if (typeof window !== 'undefined') {
try {
// Increase the number of stack frames on the client
Error.stackTraceLimit = 50
} catch {}
window.addEventListener('error', onUnhandledError)
window.addEventListener('unhandledrejection', onUnhandledRejection)
}
}