-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
eventbuilder.ts
409 lines (356 loc) · 12.8 KB
/
eventbuilder.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
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import type {
Event,
EventHint,
Exception,
ParameterizedString,
SeverityLevel,
StackFrame,
StackParser,
} from '@sentry/core';
import {
addExceptionMechanism,
addExceptionTypeValue,
extractExceptionKeysForMessage,
getClient,
isDOMError,
isDOMException,
isError,
isErrorEvent,
isEvent,
isParameterizedString,
isPlainObject,
normalizeToSize,
resolvedSyncPromise,
} from '@sentry/core';
type Prototype = { constructor: (...args: unknown[]) => unknown };
/**
* This function creates an exception from a JavaScript Error
*/
export function exceptionFromError(stackParser: StackParser, ex: Error): Exception {
// Get the frames first since Opera can lose the stack if we touch anything else first
const frames = parseStackFrames(stackParser, ex);
const exception: Exception = {
type: extractType(ex),
value: extractMessage(ex),
};
if (frames.length) {
exception.stacktrace = { frames };
}
if (exception.type === undefined && exception.value === '') {
exception.value = 'Unrecoverable error caught';
}
return exception;
}
function eventFromPlainObject(
stackParser: StackParser,
exception: Record<string, unknown>,
syntheticException?: Error,
isUnhandledRejection?: boolean,
): Event {
const client = getClient();
const normalizeDepth = client && client.getOptions().normalizeDepth;
// If we can, we extract an exception from the object properties
const errorFromProp = getErrorPropertyFromObject(exception);
const extra = {
__serialized__: normalizeToSize(exception, normalizeDepth),
};
if (errorFromProp) {
return {
exception: {
values: [exceptionFromError(stackParser, errorFromProp)],
},
extra,
};
}
const event = {
exception: {
values: [
{
type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',
value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),
} as Exception,
],
},
extra,
} satisfies Event;
if (syntheticException) {
const frames = parseStackFrames(stackParser, syntheticException);
if (frames.length) {
// event.exception.values[0] has been set above
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
event.exception.values[0]!.stacktrace = { frames };
}
}
return event;
}
function eventFromError(stackParser: StackParser, ex: Error): Event {
return {
exception: {
values: [exceptionFromError(stackParser, ex)],
},
};
}
/** Parses stack frames from an error */
function parseStackFrames(
stackParser: StackParser,
ex: Error & { framesToPop?: number; stacktrace?: string },
): StackFrame[] {
// Access and store the stacktrace property before doing ANYTHING
// else to it because Opera is not very good at providing it
// reliably in other circumstances.
const stacktrace = ex.stacktrace || ex.stack || '';
const skipLines = getSkipFirstStackStringLines(ex);
const framesToPop = getPopFirstTopFrames(ex);
try {
return stackParser(stacktrace, skipLines, framesToPop);
} catch (e) {
// no-empty
}
return [];
}
// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108
const reactMinifiedRegexp = /Minified React error #\d+;/i;
/**
* Certain known React errors contain links that would be falsely
* parsed as frames. This function check for these errors and
* returns number of the stack string lines to skip.
*/
function getSkipFirstStackStringLines(ex: Error): number {
if (ex && reactMinifiedRegexp.test(ex.message)) {
return 1;
}
return 0;
}
/**
* If error has `framesToPop` property, it means that the
* creator tells us the first x frames will be useless
* and should be discarded. Typically error from wrapper function
* which don't point to the actual location in the developer's code.
*
* Example: https://github.com/zertosh/invariant/blob/master/invariant.js#L46
*/
function getPopFirstTopFrames(ex: Error & { framesToPop?: unknown }): number {
if (typeof ex.framesToPop === 'number') {
return ex.framesToPop;
}
return 0;
}
// https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Exception
// @ts-expect-error - WebAssembly.Exception is a valid class
function isWebAssemblyException(exception: unknown): exception is WebAssembly.Exception {
// Check for support
// @ts-expect-error - WebAssembly.Exception is a valid class
if (typeof WebAssembly !== 'undefined' && typeof WebAssembly.Exception !== 'undefined') {
// @ts-expect-error - WebAssembly.Exception is a valid class
return exception instanceof WebAssembly.Exception;
} else {
return false;
}
}
/**
* Extracts from errors what we use as the exception `type` in error events.
*
* Usually, this is the `name` property on Error objects but WASM errors need to be treated differently.
*/
export function extractType(ex: Error & { message: { error?: Error } }): string | undefined {
const name = ex && ex.name;
// The name for WebAssembly.Exception Errors needs to be extracted differently.
// Context: https://github.com/getsentry/sentry-javascript/issues/13787
if (!name && isWebAssemblyException(ex)) {
// Emscripten sets array[type, message] to the "message" property on the WebAssembly.Exception object
const hasTypeInMessage = ex.message && Array.isArray(ex.message) && ex.message.length == 2;
return hasTypeInMessage ? ex.message[0] : 'WebAssembly.Exception';
}
return name;
}
/**
* There are cases where stacktrace.message is an Event object
* https://github.com/getsentry/sentry-javascript/issues/1949
* In this specific case we try to extract stacktrace.message.error.message
*/
export function extractMessage(ex: Error & { message: { error?: Error } }): string {
const message = ex && ex.message;
if (!message) {
return 'No error message';
}
if (message.error && typeof message.error.message === 'string') {
return message.error.message;
}
// Emscripten sets array[type, message] to the "message" property on the WebAssembly.Exception object
if (isWebAssemblyException(ex) && Array.isArray(ex.message) && ex.message.length == 2) {
return ex.message[1];
}
return message;
}
/**
* Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.
* @hidden
*/
export function eventFromException(
stackParser: StackParser,
exception: unknown,
hint?: EventHint,
attachStacktrace?: boolean,
): PromiseLike<Event> {
const syntheticException = (hint && hint.syntheticException) || undefined;
const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);
addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }
event.level = 'error';
if (hint && hint.event_id) {
event.event_id = hint.event_id;
}
return resolvedSyncPromise(event);
}
/**
* Builds and Event from a Message
* @hidden
*/
export function eventFromMessage(
stackParser: StackParser,
message: ParameterizedString,
level: SeverityLevel = 'info',
hint?: EventHint,
attachStacktrace?: boolean,
): PromiseLike<Event> {
const syntheticException = (hint && hint.syntheticException) || undefined;
const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);
event.level = level;
if (hint && hint.event_id) {
event.event_id = hint.event_id;
}
return resolvedSyncPromise(event);
}
/**
* @hidden
*/
export function eventFromUnknownInput(
stackParser: StackParser,
exception: unknown,
syntheticException?: Error,
attachStacktrace?: boolean,
isUnhandledRejection?: boolean,
): Event {
let event: Event;
if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {
// If it is an ErrorEvent with `error` property, extract it to get actual Error
const errorEvent = exception as ErrorEvent;
return eventFromError(stackParser, errorEvent.error as Error);
}
// If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name
// and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be
// `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.
//
// https://developer.mozilla.org/en-US/docs/Web/API/DOMError
// https://developer.mozilla.org/en-US/docs/Web/API/DOMException
// https://webidl.spec.whatwg.org/#es-DOMException-specialness
if (isDOMError(exception) || isDOMException(exception as DOMException)) {
const domException = exception as DOMException;
if ('stack' in (exception as Error)) {
event = eventFromError(stackParser, exception as Error);
} else {
const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');
const message = domException.message ? `${name}: ${domException.message}` : name;
event = eventFromString(stackParser, message, syntheticException, attachStacktrace);
addExceptionTypeValue(event, message);
}
if ('code' in domException) {
// eslint-disable-next-line deprecation/deprecation
event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };
}
return event;
}
if (isError(exception)) {
// we have a real Error object, do nothing
return eventFromError(stackParser, exception);
}
if (isPlainObject(exception) || isEvent(exception)) {
// If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize
// it manually. This will allow us to group events based on top-level keys which is much better than creating a new
// group on any key/value change.
const objectException = exception as Record<string, unknown>;
event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);
addExceptionMechanism(event, {
synthetic: true,
});
return event;
}
// If none of previous checks were valid, then it means that it's not:
// - an instance of DOMError
// - an instance of DOMException
// - an instance of Event
// - an instance of Error
// - a valid ErrorEvent (one with an error property)
// - a plain Object
//
// So bail out and capture it as a simple message:
event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);
addExceptionTypeValue(event, `${exception}`, undefined);
addExceptionMechanism(event, {
synthetic: true,
});
return event;
}
function eventFromString(
stackParser: StackParser,
message: ParameterizedString,
syntheticException?: Error,
attachStacktrace?: boolean,
): Event {
const event: Event = {};
if (attachStacktrace && syntheticException) {
const frames = parseStackFrames(stackParser, syntheticException);
if (frames.length) {
event.exception = {
values: [{ value: message, stacktrace: { frames } }],
};
}
addExceptionMechanism(event, { synthetic: true });
}
if (isParameterizedString(message)) {
const { __sentry_template_string__, __sentry_template_values__ } = message;
event.logentry = {
message: __sentry_template_string__,
params: __sentry_template_values__,
};
return event;
}
event.message = message;
return event;
}
function getNonErrorObjectExceptionValue(
exception: Record<string, unknown>,
{ isUnhandledRejection }: { isUnhandledRejection?: boolean },
): string {
const keys = extractExceptionKeysForMessage(exception);
const captureType = isUnhandledRejection ? 'promise rejection' : 'exception';
// Some ErrorEvent instances do not have an `error` property, which is why they are not handled before
// We still want to try to get a decent message for these cases
if (isErrorEvent(exception)) {
return `Event \`ErrorEvent\` captured as ${captureType} with message \`${exception.message}\``;
}
if (isEvent(exception)) {
const className = getObjectClassName(exception);
return `Event \`${className}\` (type=${exception.type}) captured as ${captureType}`;
}
return `Object captured as ${captureType} with keys: ${keys}`;
}
function getObjectClassName(obj: unknown): string | undefined | void {
try {
const prototype: Prototype | null = Object.getPrototypeOf(obj);
return prototype ? prototype.constructor.name : undefined;
} catch (e) {
// ignore errors here
}
}
/** If a plain object has a property that is an `Error`, return this error. */
function getErrorPropertyFromObject(obj: Record<string, unknown>): Error | undefined {
for (const prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
const value = obj[prop];
if (value instanceof Error) {
return value;
}
}
}
return undefined;
}