-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathErrorBoundary.tsx
More file actions
298 lines (256 loc) · 7.07 KB
/
ErrorBoundary.tsx
File metadata and controls
298 lines (256 loc) · 7.07 KB
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import {
type BugSplat,
type BugSplatAttachment,
type BugSplatResponse,
} from 'bugsplat';
import {
Component,
type ErrorInfo,
type JSX,
isValidElement,
type ReactElement,
type ReactNode,
} from 'react';
import { appScope } from './appScope';
import type { Scope } from './scope';
/**
* Shallowly compare two arrays to determine if they are different.
*
* Uses `Object.is` to perform comparison on each item.
*
* @returns true if arrays are the same length and shallowly equal
*/
function isArrayDiff(a: unknown[] = [], b: unknown[] = []) {
if (a.length !== b.length) {
return true;
}
return a.some((item, index) => !Object.is(item, b[index]));
}
export interface FallbackProps {
/**
* Error that caused crash
*/
error: Error;
/**
* Component stack trace leading to error
*/
componentStack: string | null;
/**
* Crash post response
*/
response: BugSplatResponse | null;
/**
* Reset error boundary state.
*
* This will pass any arguments to the end of onReset when it is called
*/
resetErrorBoundary: (...args: unknown[]) => void;
}
export type FallbackElement = ReactElement | null;
export type FallbackRender = (props: FallbackProps) => FallbackElement;
interface InternalErrorBoundaryProps {
/**
* Callback called before error post to BugSplat.
*
* This will be awaited if it is a promise
*/
beforePost: (
bugSplat: BugSplat,
error: Error | null,
componentStack: string | null
) => void | Promise<void>;
/**
* Callback called when ErrorBoundary catches an error in componentDidCatch()
*
* This will be awaited if it is a promise
*/
onError: (
error: Error,
componentStack: string,
response: BugSplatResponse | null
) => void | Promise<void>;
/**
* Callback called on componentDidMount().
*/
onMount: () => void;
/**
* Callback called on componentWillUnmount().
*/
onUnmount: (state: ErrorBoundaryState) => void;
/**
* Callback called before ErrorBoundary resets internal state,
* resulting in rendering children again. This should be
* used to ensure that rerendering of children would not
* repeat the same error that occurred.
*
* *This method is not called when ErrorBoundary is reset from a
* change in resetKeys - use onResetKeysChange for that.*
* @param state - Current error boundary state
* @param ...args - Additional arguments passed from where it is called
*/
onReset: (state: ErrorBoundaryState, ...args: unknown[]) => void;
/**
* Callback called when keys passed to resetKeys are changed.
*/
onResetKeysChange: (prevResetKeys?: unknown[], resetKeys?: unknown[]) => void;
/**
* Array of values passed from parent scope. When ErrorBoundary
* is in an error state, it will check each passed value
* and automatically reset if any of the values have changed.
*/
resetKeys?: unknown[];
/**
* Provide a fallback to render when ErrorBoundary catches an error.
* Not required, but it is highly recommended to provide a value for this.
*
* This can be an element or a function that renders an element.
*/
fallback?: FallbackElement | FallbackRender;
/**
* If true, caught errors will not be automatically posted to BugSplat.
*/
disablePost?: boolean;
/**
* Child elements to be rendered when there is no error
*/
children?: ReactNode | ReactNode[];
/**
* __Advanced Use__
*
* Object used by ErrorBoundary to retrieve a BugSplat client instance.
*
* Advanced users can extend the `BugSplat` class and use this property
* to pass their own scope that will inject the client for use by
* ErrorBoundary.
*/
scope: Pick<Scope, 'getClient' | 'getCreateComponentStackAttachment'>;
}
export type ErrorBoundaryProps = JSX.LibraryManagedAttributes<
typeof ErrorBoundary,
InternalErrorBoundaryProps
>;
export interface ErrorBoundaryState {
/**
* Rendering error; if one occurred.
*/
error: Error | null;
/**
* Component stack trace of a rendering error; if one occurred.
*/
componentStack: string | null;
/**
* Response from most recent BugSplat crash post
*/
response: BugSplatResponse | null;
}
const INITIAL_STATE: ErrorBoundaryState = {
error: null,
componentStack: null,
response: null,
};
/**
* Empty function that does nothing
*
* Useful as a placeholder
*/
function noop(..._args: unknown[]) {
// this comment allows empty function
}
/**
* Handle errors that occur during rendering by wrapping
* your component tree with ErrorBoundary. Any number of ErrorBoundary
* components can be rendered in the tree and any rendering error will
* propagate to the nearest one.
*/
export class ErrorBoundary extends Component<
InternalErrorBoundaryProps,
ErrorBoundaryState
> {
static getDerivedStateFromError(error: Error) {
return { error };
}
static defaultProps: InternalErrorBoundaryProps = {
beforePost: noop,
onError: noop,
onMount: noop,
onReset: noop,
onResetKeysChange: noop,
onUnmount: noop,
disablePost: false,
scope: appScope,
};
state = INITIAL_STATE;
componentDidMount() {
this.props.onMount();
}
componentDidUpdate(
prevProps: ErrorBoundaryProps,
prevState: ErrorBoundaryState
) {
const { error } = this.state;
const { resetKeys, onResetKeysChange } = this.props;
if (
error !== null &&
prevState.error !== null &&
isArrayDiff(prevProps.resetKeys, resetKeys)
) {
onResetKeysChange(prevProps.resetKeys, resetKeys);
this.reset();
}
}
componentDidCatch(error: Error, { componentStack }: ErrorInfo) {
const stack = componentStack ?? null;
this.setState({ error, componentStack: stack });
this.handleError(error, stack ?? '').catch(console.error);
}
componentWillUnmount() {
this.props.onUnmount({ ...this.state });
}
async dispatchPost(error: Error, componentStack: string) {
const { beforePost, disablePost, scope } = this.props;
const client = scope.getClient();
if (!client || disablePost) {
return null;
}
await beforePost(client, error, componentStack);
return client.post(error, {
attachments: componentStack
? [scope.getCreateComponentStackAttachment()(componentStack)]
: [],
});
}
async handleError(error: Error, componentStack: string) {
const response = await this.dispatchPost(error, componentStack);
this.setState({ response });
return this.props.onError(error, componentStack, response);
}
resetErrorBoundary = (...args: unknown[]) => {
this.props.onReset({ ...this.state }, ...args);
this.reset();
};
reset() {
this.setState(INITIAL_STATE);
}
render() {
const {
state: { error, componentStack, response },
props: { fallback, children },
resetErrorBoundary,
} = this;
if (!error) {
return children;
}
if (isValidElement(fallback)) {
return fallback;
}
if (typeof fallback === 'function') {
return fallback({
error,
componentStack,
response,
resetErrorBoundary,
});
}
return null;
}
}