-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy patherrorboundary.tsx
221 lines (189 loc) · 7.41 KB
/
errorboundary.tsx
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
import type { ReportDialogOptions } from '@sentry/browser';
import { getClient, showReportDialog, withScope } from '@sentry/browser';
import { logger } from '@sentry/core';
import type { Scope } from '@sentry/core';
import hoistNonReactStatics from 'hoist-non-react-statics';
import * as React from 'react';
import { DEBUG_BUILD } from './debug-build';
import { captureReactException } from './error';
export const UNKNOWN_COMPONENT = 'unknown';
export type FallbackRender = (errorData: {
error: unknown;
componentStack: string;
eventId: string;
resetError(): void;
}) => React.ReactElement;
export type ErrorBoundaryProps = {
children?: React.ReactNode | (() => React.ReactNode);
/** If a Sentry report dialog should be rendered on error */
showDialog?: boolean | undefined;
/**
* Options to be passed into the Sentry report dialog.
* No-op if {@link showDialog} is false.
*/
dialogOptions?: ReportDialogOptions | undefined;
/**
* A fallback component that gets rendered when the error boundary encounters an error.
*
* Can either provide a React Component, or a function that returns React Component as
* a valid fallback prop. If a function is provided, the function will be called with
* the error, the component stack, and an function that resets the error boundary on error.
*
*/
fallback?: React.ReactElement | FallbackRender | undefined;
/**
* If set to `true` or `false`, the error `handled` property will be set to the given value.
* If unset, the default behaviour is to rely on the presence of the `fallback` prop to determine
* if the error was handled or not.
*/
handled?: boolean | undefined;
/** Called when the error boundary encounters an error */
onError?: ((error: unknown, componentStack: string | undefined, eventId: string) => void) | undefined;
/** Called on componentDidMount() */
onMount?: (() => void) | undefined;
/** Called if resetError() is called from the fallback render props function */
onReset?: ((error: unknown, componentStack: string | null | undefined, eventId: string | null) => void) | undefined;
/** Called on componentWillUnmount() */
onUnmount?: ((error: unknown, componentStack: string | null | undefined, eventId: string | null) => void) | undefined;
/** Called before the error is captured by Sentry, allows for you to add tags or context using the scope */
beforeCapture?: ((scope: Scope, error: unknown, componentStack: string | undefined) => void) | undefined;
};
type ErrorBoundaryState =
| {
componentStack: null;
error: null;
eventId: null;
}
| {
componentStack: React.ErrorInfo['componentStack'];
error: unknown;
eventId: string;
};
const INITIAL_STATE = {
componentStack: null,
error: null,
eventId: null,
};
/**
* A ErrorBoundary component that logs errors to Sentry.
* NOTE: If you are a Sentry user, and you are seeing this stack frame, it means the
* Sentry React SDK ErrorBoundary caught an error invoking your application code. This
* is expected behavior and NOT indicative of a bug with the Sentry React SDK.
*/
class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
public state: ErrorBoundaryState;
private readonly _openFallbackReportDialog: boolean;
private _lastEventId?: string;
private _cleanupHook?: () => void;
public constructor(props: ErrorBoundaryProps) {
super(props);
this.state = INITIAL_STATE;
this._openFallbackReportDialog = true;
const client = getClient();
if (client && props.showDialog) {
this._openFallbackReportDialog = false;
this._cleanupHook = client.on('afterSendEvent', event => {
if (!event.type && this._lastEventId && event.event_id === this._lastEventId) {
showReportDialog({ ...props.dialogOptions, eventId: this._lastEventId });
}
});
}
}
public componentDidCatch(error: unknown, errorInfo: React.ErrorInfo): void {
const { componentStack } = errorInfo;
// TODO(v9): Remove this check and type `componentStack` to be React.ErrorInfo['componentStack'].
const passedInComponentStack: string | undefined = componentStack == null ? undefined : componentStack;
const { beforeCapture, onError, showDialog, dialogOptions } = this.props;
withScope(scope => {
if (beforeCapture) {
beforeCapture(scope, error, passedInComponentStack);
}
const handled = this.props.handled != null ? this.props.handled : !!this.props.fallback;
const eventId = captureReactException(error, errorInfo, { mechanism: { handled } });
if (onError) {
onError(error, passedInComponentStack, eventId);
}
if (showDialog) {
this._lastEventId = eventId;
if (this._openFallbackReportDialog) {
showReportDialog({ ...dialogOptions, eventId });
}
}
// componentDidCatch is used over getDerivedStateFromError
// so that componentStack is accessible through state.
this.setState({ error, componentStack, eventId });
});
}
public componentDidMount(): void {
const { onMount } = this.props;
if (onMount) {
onMount();
}
}
public componentWillUnmount(): void {
const { error, componentStack, eventId } = this.state;
const { onUnmount } = this.props;
if (onUnmount) {
onUnmount(error, componentStack, eventId);
}
if (this._cleanupHook) {
this._cleanupHook();
this._cleanupHook = undefined;
}
}
public resetErrorBoundary: () => void = () => {
const { onReset } = this.props;
const { error, componentStack, eventId } = this.state;
if (onReset) {
onReset(error, componentStack, eventId);
}
this.setState(INITIAL_STATE);
};
public render(): React.ReactNode {
const { fallback, children } = this.props;
const state = this.state;
if (state.error) {
let element: React.ReactElement | undefined = undefined;
if (typeof fallback === 'function') {
element = React.createElement(fallback, {
error: state.error,
componentStack: state.componentStack as string,
resetError: this.resetErrorBoundary,
eventId: state.eventId as string,
});
} else {
element = fallback;
}
if (React.isValidElement(element)) {
return element;
}
if (fallback) {
DEBUG_BUILD && logger.warn('fallback did not produce a valid ReactElement');
}
// Fail gracefully if no fallback provided or is not valid
return null;
}
if (typeof children === 'function') {
return (children as () => React.ReactNode)();
}
return children;
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function withErrorBoundary<P extends Record<string, any>>(
WrappedComponent: React.ComponentType<P>,
errorBoundaryOptions: ErrorBoundaryProps,
): React.FC<P> {
const componentDisplayName = WrappedComponent.displayName || WrappedComponent.name || UNKNOWN_COMPONENT;
const Wrapped: React.FC<P> = (props: P) => (
<ErrorBoundary {...errorBoundaryOptions}>
<WrappedComponent {...props} />
</ErrorBoundary>
);
Wrapped.displayName = `errorBoundary(${componentDisplayName})`;
// Copy over static methods from Wrapped component to Profiler HOC
// See: https://reactjs.org/docs/higher-order-components.html#static-methods-must-be-copied-over
hoistNonReactStatics(Wrapped, WrappedComponent);
return Wrapped;
}
export { ErrorBoundary, withErrorBoundary };