Skip to content

Commit 537db38

Browse files
committed
ref(browser): Extract global handlers private methods
- Move hub and client getters out to a common call and pass them down - Check for integration existence early on - Move private methods into regular functions as they don't use class props
1 parent 5216184 commit 537db38

File tree

1 file changed

+98
-95
lines changed

1 file changed

+98
-95
lines changed
Lines changed: 98 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
2-
import { getCurrentHub } from '@sentry/core';
3-
import { Event, Integration, Primitive, Severity } from '@sentry/types';
2+
import { Event, EventProcessor, Hub, Integration, Primitive, Severity } from '@sentry/types';
43
import {
54
addExceptionMechanism,
65
addInstrumentationHandler,
@@ -52,22 +51,29 @@ export class GlobalHandlers implements Integration {
5251
/**
5352
* @inheritDoc
5453
*/
55-
public setupOnce(): void {
54+
public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {
5655
Error.stackTraceLimit = 50;
5756

57+
const hub = getCurrentHub();
58+
if (!hub.getIntegration(GlobalHandlers)) {
59+
return;
60+
}
61+
const client = hub.getClient();
62+
const attachStacktrace = client && client.getOptions().attachStacktrace;
63+
5864
if (this._options.onerror) {
59-
logger.log('Global Handler attached: onerror');
60-
this._installGlobalOnErrorHandler();
65+
globalHandlerLog('onerror');
66+
this._installGlobalOnErrorHandler(hub, attachStacktrace);
6167
}
6268

6369
if (this._options.onunhandledrejection) {
64-
logger.log('Global Handler attached: onunhandledrejection');
65-
this._installGlobalOnUnhandledRejectionHandler();
70+
globalHandlerLog('onunhandledrejection');
71+
this._installGlobalOnUnhandledRejectionHandler(hub, attachStacktrace);
6672
}
6773
}
6874

6975
/** JSDoc */
70-
private _installGlobalOnErrorHandler(): void {
76+
private _installGlobalOnErrorHandler(hub: Hub, attachStacktrace: boolean | undefined): void {
7177
if (this._onErrorHandlerInstalled) {
7278
return;
7379
}
@@ -76,21 +82,18 @@ export class GlobalHandlers implements Integration {
7682
// eslint-disable-next-line @typescript-eslint/no-explicit-any
7783
callback: (data: { msg: any; url: any; line: any; column: any; error: any }) => {
7884
const error = data.error;
79-
const currentHub = getCurrentHub();
80-
const hasIntegration = currentHub.getIntegration(GlobalHandlers);
8185
const isFailedOwnDelivery = error && error.__sentry_own_request__ === true;
8286

83-
if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) {
87+
if (shouldIgnoreOnError() || isFailedOwnDelivery) {
8488
return;
8589
}
8690

87-
const client = currentHub.getClient();
8891
const event =
8992
error === undefined && isString(data.msg)
90-
? this._eventFromIncompleteOnError(data.msg, data.url, data.line, data.column)
91-
: this._enhanceEventWithInitialFrame(
93+
? _eventFromIncompleteOnError(data.msg, data.url, data.line, data.column)
94+
: _enhanceEventWithInitialFrame(
9295
eventFromUnknownInput(error || data.msg, undefined, {
93-
attachStacktrace: client && client.getOptions().attachStacktrace,
96+
attachStacktrace,
9497
rejection: false,
9598
}),
9699
data.url,
@@ -103,7 +106,7 @@ export class GlobalHandlers implements Integration {
103106
type: 'onerror',
104107
});
105108

106-
currentHub.captureEvent(event, {
109+
hub.captureEvent(event, {
107110
originalException: error,
108111
});
109112
},
@@ -114,7 +117,7 @@ export class GlobalHandlers implements Integration {
114117
}
115118

116119
/** JSDoc */
117-
private _installGlobalOnUnhandledRejectionHandler(): void {
120+
private _installGlobalOnUnhandledRejectionHandler(hub: Hub, attachStacktrace: boolean | undefined): void {
118121
if (this._onUnhandledRejectionHandlerInstalled) {
119122
return;
120123
}
@@ -143,19 +146,15 @@ export class GlobalHandlers implements Integration {
143146
// no-empty
144147
}
145148

146-
const currentHub = getCurrentHub();
147-
const hasIntegration = currentHub.getIntegration(GlobalHandlers);
148149
const isFailedOwnDelivery = error && error.__sentry_own_request__ === true;
149-
150-
if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) {
150+
if (shouldIgnoreOnError() || isFailedOwnDelivery) {
151151
return true;
152152
}
153153

154-
const client = currentHub.getClient();
155154
const event = isPrimitive(error)
156-
? this._eventFromRejectionWithPrimitive(error)
155+
? _eventFromRejectionWithPrimitive(error)
157156
: eventFromUnknownInput(error, undefined, {
158-
attachStacktrace: client && client.getOptions().attachStacktrace,
157+
attachStacktrace,
159158
rejection: true,
160159
});
161160

@@ -166,7 +165,7 @@ export class GlobalHandlers implements Integration {
166165
type: 'onunhandledrejection',
167166
});
168167

169-
currentHub.captureEvent(event, {
168+
hub.captureEvent(event, {
170169
originalException: error,
171170
});
172171

@@ -177,81 +176,85 @@ export class GlobalHandlers implements Integration {
177176

178177
this._onUnhandledRejectionHandlerInstalled = true;
179178
}
179+
}
180180

181-
/**
182-
* This function creates a stack from an old, error-less onerror handler.
183-
*/
184-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
185-
private _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {
186-
const ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
187-
188-
// If 'message' is ErrorEvent, get real message from inside
189-
let message = isErrorEvent(msg) ? msg.message : msg;
190-
let name;
191-
192-
const groups = message.match(ERROR_TYPES_RE);
193-
if (groups) {
194-
name = groups[1];
195-
message = groups[2];
196-
}
197-
198-
const event = {
199-
exception: {
200-
values: [
201-
{
202-
type: name || 'Error',
203-
value: message,
204-
},
205-
],
206-
},
207-
};
181+
/**
182+
* Create an event from a promise rejection where the `reason` is a primitive.
183+
*
184+
* @param reason: The `reason` property of the promise rejection
185+
* @returns An Event object with an appropriate `exception` value
186+
*/
187+
function _eventFromRejectionWithPrimitive(reason: Primitive): Event {
188+
return {
189+
exception: {
190+
values: [
191+
{
192+
type: 'UnhandledRejection',
193+
// String() is needed because the Primitive type includes symbols (which can't be automatically stringified)
194+
value: `Non-Error promise rejection captured with value: ${String(reason)}`,
195+
},
196+
],
197+
},
198+
};
199+
}
208200

209-
return this._enhanceEventWithInitialFrame(event, url, line, column);
201+
/**
202+
* This function creates a stack from an old, error-less onerror handler.
203+
*/
204+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
205+
function _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {
206+
const ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
207+
208+
// If 'message' is ErrorEvent, get real message from inside
209+
let message = isErrorEvent(msg) ? msg.message : msg;
210+
let name;
211+
212+
const groups = message.match(ERROR_TYPES_RE);
213+
if (groups) {
214+
name = groups[1];
215+
message = groups[2];
210216
}
211217

212-
/**
213-
* Create an event from a promise rejection where the `reason` is a primitive.
214-
*
215-
* @param reason: The `reason` property of the promise rejection
216-
* @returns An Event object with an appropriate `exception` value
217-
*/
218-
private _eventFromRejectionWithPrimitive(reason: Primitive): Event {
219-
return {
220-
exception: {
221-
values: [
222-
{
223-
type: 'UnhandledRejection',
224-
// String() is needed because the Primitive type includes symbols (which can't be automatically stringified)
225-
value: `Non-Error promise rejection captured with value: ${String(reason)}`,
226-
},
227-
],
228-
},
229-
};
218+
const event = {
219+
exception: {
220+
values: [
221+
{
222+
type: name || 'Error',
223+
value: message,
224+
},
225+
],
226+
},
227+
};
228+
229+
return _enhanceEventWithInitialFrame(event, url, line, column);
230+
}
231+
232+
/** JSDoc */
233+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
234+
function _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {
235+
event.exception = event.exception || {};
236+
event.exception.values = event.exception.values || [];
237+
event.exception.values[0] = event.exception.values[0] || {};
238+
event.exception.values[0].stacktrace = event.exception.values[0].stacktrace || {};
239+
event.exception.values[0].stacktrace.frames = event.exception.values[0].stacktrace.frames || [];
240+
241+
const colno = isNaN(parseInt(column, 10)) ? undefined : column;
242+
const lineno = isNaN(parseInt(line, 10)) ? undefined : line;
243+
const filename = isString(url) && url.length > 0 ? url : getLocationHref();
244+
245+
if (event.exception.values[0].stacktrace.frames.length === 0) {
246+
event.exception.values[0].stacktrace.frames.push({
247+
colno,
248+
filename,
249+
function: '?',
250+
in_app: true,
251+
lineno,
252+
});
230253
}
231254

232-
/** JSDoc */
233-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
234-
private _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {
235-
event.exception = event.exception || {};
236-
event.exception.values = event.exception.values || [];
237-
event.exception.values[0] = event.exception.values[0] || {};
238-
event.exception.values[0].stacktrace = event.exception.values[0].stacktrace || {};
239-
event.exception.values[0].stacktrace.frames = event.exception.values[0].stacktrace.frames || [];
240-
241-
const colno = isNaN(parseInt(column, 10)) ? undefined : column;
242-
const lineno = isNaN(parseInt(line, 10)) ? undefined : line;
243-
const filename = isString(url) && url.length > 0 ? url : getLocationHref();
244-
245-
if (event.exception.values[0].stacktrace.frames.length === 0) {
246-
event.exception.values[0].stacktrace.frames.push({
247-
colno,
248-
filename,
249-
function: '?',
250-
in_app: true,
251-
lineno,
252-
});
253-
}
255+
return event;
256+
}
254257

255-
return event;
256-
}
258+
function globalHandlerLog(type: string): void {
259+
logger.log(`Global Handler attached: ${type}`);
257260
}

0 commit comments

Comments
 (0)