-
-
Notifications
You must be signed in to change notification settings - Fork 337
/
reactnativeerrorhandlers.ts
180 lines (152 loc) · 5.32 KB
/
reactnativeerrorhandlers.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
import { captureException, convertIntegrationFnToClass, getClient, getCurrentScope } from '@sentry/core';
import type { EventHint, Integration, IntegrationClass, IntegrationFnResult, SeverityLevel } from '@sentry/types';
import { addExceptionMechanism, logger } from '@sentry/utils';
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> = {},
): IntegrationFnResult => {
return {
name: INTEGRATION_NAME,
setupOnce: () =>
setup({
onerror: true,
onunhandledrejection: true,
patchGlobalPromise: true,
...options,
}),
};
};
/**
* ReactNativeErrorHandlers Integration
*
* @deprecated Use `reactNativeErrorHandlersIntegration()` instead.
*/
// eslint-disable-next-line deprecation/deprecation
export const ReactNativeErrorHandlers = convertIntegrationFnToClass(
INTEGRATION_NAME,
reactNativeErrorHandlersIntegration,
) as IntegrationClass<Integration> & {
new (options?: Partial<ReactNativeErrorHandlersOptions>): Integration;
};
function setup(options: ReactNativeErrorHandlersOptions): void {
options.onunhandledrejection && setupUnhandledRejectionsTracking(options.patchGlobalPromise);
options.onerror && setupErrorUtilsGlobalHandler();
}
/**
* Setup unhandled promise rejection tracking
*/
function setupUnhandledRejectionsTracking(patchGlobalPromise: boolean): void {
if (patchGlobalPromise) {
polyfillPromise();
}
attachUnhandledRejectionHandler();
checkPromiseAndWarn();
}
function attachUnhandledRejectionHandler(): void {
const tracking = requireRejectionTracking();
const promiseRejectionTrackingOptions: PromiseRejectionTrackingOptions = {
onUnhandled: (id, rejection = {}) => {
// eslint-disable-next-line no-console
console.warn(`Possible Unhandled Promise Rejection (id: ${id}):\n${rejection}`);
},
onHandled: id => {
// eslint-disable-next-line no-console
console.warn(
`Promise Rejection Handled (id: ${id})\n` +
'This means you can ignore any previous messages of the form ' +
`"Possible Unhandled Promise Rejection (id: ${id}):"`,
);
},
};
tracking.enable({
allRejections: true,
onUnhandled: (id: string, error: unknown) => {
if (__DEV__) {
promiseRejectionTrackingOptions.onUnhandled(id, error);
}
captureException(error, {
data: { id },
originalException: error,
syntheticException: isErrorLike(error) ? undefined : createSyntheticError(),
});
},
onHandled: (id: string) => {
promiseRejectionTrackingOptions.onHandled(id);
},
});
}
function setupErrorUtilsGlobalHandler(): void {
let handlingFatal = false;
const errorUtils = RN_GLOBAL_OBJ.ErrorUtils;
if (!errorUtils) {
logger.warn('ErrorUtils not found. Can be caused by different environment for example react-native-web.');
return;
}
const defaultHandler = errorUtils.getGlobalHandler && errorUtils.getGlobalHandler();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
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) {
logger.log('Encountered multiple fatals in a row. The latest:', error);
return;
}
handlingFatal = true;
}
const client = getClient();
if (!client) {
logger.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;
}
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().shutdownTimeout || 2000).then(
() => {
defaultHandler(error, isFatal);
},
(reason: unknown) => {
logger.error('[ReactNativeErrorHandlers] Error while flushing the event cache after uncaught error.', reason);
},
);
});
}