-
-
Notifications
You must be signed in to change notification settings - Fork 360
Expand file tree
/
Copy pathreactnativeerrorhandlers.ts
More file actions
230 lines (197 loc) · 7.49 KB
/
reactnativeerrorhandlers.ts
File metadata and controls
230 lines (197 loc) · 7.49 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
import type { EventHint, Integration, SeverityLevel } from '@sentry/core';
import {
addExceptionMechanism,
addGlobalUnhandledRejectionInstrumentationHandler,
captureException,
debug,
getClient,
getCurrentScope,
} from '@sentry/core';
import type { ReactNativeClientOptions } from '../options';
import { isHermesEnabled, isWeb } from '../utils/environment';
import { createSyntheticError, isErrorLike } from '../utils/error';
import { RN_GLOBAL_OBJ } from '../utils/worldwide';
import { checkPromiseAndWarn, polyfillPromise, requireRejectionTracking } from './reactnativeerrorhandlersutils';
const INTEGRATION_NAME = 'ReactNativeErrorHandlers';
/** ReactNativeErrorHandlers Options */
interface ReactNativeErrorHandlersOptions {
onerror: boolean;
onunhandledrejection: boolean;
patchGlobalPromise: boolean;
}
interface PromiseRejectionTrackingOptions {
onUnhandled: (id: string, error: unknown) => void;
onHandled: (id: string) => void;
}
/** ReactNativeErrorHandlers Integration */
export const reactNativeErrorHandlersIntegration = (
options: Partial<ReactNativeErrorHandlersOptions> = {},
): Integration => {
return {
name: INTEGRATION_NAME,
setupOnce: () =>
setup({
onerror: true,
onunhandledrejection: true,
patchGlobalPromise: true,
...options,
}),
};
};
function setup(options: ReactNativeErrorHandlersOptions): void {
options.onunhandledrejection && setupUnhandledRejectionsTracking(options.patchGlobalPromise);
options.onerror && setupErrorUtilsGlobalHandler();
}
/**
* Setup unhandled promise rejection tracking
*/
function setupUnhandledRejectionsTracking(patchGlobalPromise: boolean): void {
try {
if (
isHermesEnabled() &&
RN_GLOBAL_OBJ.HermesInternal?.enablePromiseRejectionTracker &&
RN_GLOBAL_OBJ?.HermesInternal?.hasPromise?.()
) {
debug.log('Using Hermes native promise rejection tracking');
RN_GLOBAL_OBJ.HermesInternal.enablePromiseRejectionTracker({
allRejections: true,
onUnhandled: promiseRejectionTrackingOptions.onUnhandled,
onHandled: promiseRejectionTrackingOptions.onHandled,
});
debug.log('Unhandled promise rejections will be caught by Sentry.');
} else if (isWeb()) {
debug.log('Using Browser JS promise rejection tracking for React Native Web');
// Use Sentry's built-in global unhandled rejection handler
addGlobalUnhandledRejectionInstrumentationHandler((error: unknown) => {
captureException(error, {
originalException: error,
syntheticException: isErrorLike(error) ? undefined : createSyntheticError(),
mechanism: { handled: false, type: 'onunhandledrejection' },
});
});
} else if (patchGlobalPromise) {
// For JSC and other environments, use the existing approach
polyfillPromise();
attachUnhandledRejectionHandler();
checkPromiseAndWarn();
} else {
// For JSC and other environments, patching was disabled by user configuration
debug.log('Unhandled promise rejections will not be caught by Sentry.');
}
} catch (e) {
debug.warn(
'Failed to set up promise rejection tracking. ' +
'Unhandled promise rejections will not be caught by Sentry.' +
'See https://docs.sentry.io/platforms/react-native/troubleshooting/ for more details.',
);
}
}
const promiseRejectionTrackingOptions: PromiseRejectionTrackingOptions = {
onUnhandled: (id, error: unknown, rejection = {}) => {
if (__DEV__) {
debug.warn(`Possible Unhandled Promise Rejection (id: ${id}):\n${rejection}`);
}
// Marking the rejection as handled to avoid breaking crash rate calculations.
// See: https://github.com/getsentry/sentry-react-native/issues/4141
captureException(error, {
data: { id },
originalException: error,
syntheticException: isErrorLike(error) ? undefined : createSyntheticError(),
mechanism: { handled: true, type: 'onunhandledrejection' },
});
},
onHandled: id => {
if (__DEV__) {
debug.warn(
`Promise Rejection Handled (id: ${id})\n` +
'This means you can ignore any previous messages of the form ' +
`"Possible Unhandled Promise Rejection (id: ${id}):"`,
);
}
},
};
function attachUnhandledRejectionHandler(): void {
const tracking = requireRejectionTracking();
tracking.enable({
allRejections: true,
onUnhandled: promiseRejectionTrackingOptions.onUnhandled,
onHandled: promiseRejectionTrackingOptions.onHandled,
});
}
function setupErrorUtilsGlobalHandler(): void {
let handlingFatal = false;
const errorUtils = RN_GLOBAL_OBJ.ErrorUtils;
if (!errorUtils) {
debug.warn('ErrorUtils not found. Can be caused by different environment for example react-native-web.');
return;
}
// oxlint-disable-next-line typescript-eslint(no-unsafe-member-access)
const defaultHandler = errorUtils.getGlobalHandler?.();
// oxlint-disable-next-line typescript-eslint(no-explicit-any), typescript-eslint(no-unsafe-member-access)
errorUtils.setGlobalHandler(async (error: any, isFatal?: boolean) => {
// We want to handle fatals, but only in production mode.
const shouldHandleFatal = isFatal && !__DEV__;
if (shouldHandleFatal) {
if (handlingFatal) {
debug.log('Encountered multiple fatals in a row. The latest:', error);
return;
}
handlingFatal = true;
}
const client = getClient();
if (!client) {
debug.error('Sentry client is missing, the error event might be lost.', error);
// If there is no client something is fishy, anyway we call the default handler
defaultHandler(error, isFatal);
return;
}
// React render errors may arrive without useful frames in .stack but with a
// .componentStack (set by ReactFiberErrorDialog) that contains component
// locations with bundle offsets. Use componentStack as a fallback so
// eventFromException can extract frames with source locations.
// oxlint-disable-next-line typescript-eslint(no-unsafe-member-access)
if (error?.componentStack && (!error.stack || !hasStackFrames(error.stack))) {
// oxlint-disable-next-line typescript-eslint(no-unsafe-member-access)
error.stack = `${error.message || 'Error'}${error.componentStack}`;
}
const hint: EventHint = {
originalException: error,
attachments: getCurrentScope().getScopeData().attachments,
};
const event = await client.eventFromException(error, hint);
if (isFatal) {
event.level = 'fatal' as SeverityLevel;
addExceptionMechanism(event, {
handled: false,
type: 'onerror',
});
} else {
event.level = 'error';
addExceptionMechanism(event, {
handled: true,
type: 'generic',
});
}
client.captureEvent(event, hint);
if (__DEV__) {
// If in dev, we call the default handler anyway and hope the error will be sent
// Just for a better dev experience
defaultHandler(error, isFatal);
return;
}
void client.flush((client.getOptions() as ReactNativeClientOptions).shutdownTimeout || 2000).then(
() => {
defaultHandler(error, isFatal);
},
(reason: unknown) => {
debug.error('[ReactNativeErrorHandlers] Error while flushing the event cache after uncaught error.', reason);
},
);
});
}
/**
* Checks if a stack trace string contains at least one frame line.
*/
function hasStackFrames(stack: unknown): boolean {
return typeof stack === 'string' && stack.includes('\n');
}