Skip to content

Commit 9f07f99

Browse files
authored
fix(angular): Guard ErrorEvent check in ErrorHandler to avoid throwing in Node environments (#12892)
Add a guard for referencing `ErrorEvent` which is only available in browser environments but not in Node.
1 parent 963eab7 commit 9f07f99

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

packages/angular/src/errorhandler.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ function extractHttpModuleError(error: HttpErrorResponse): string | Error {
3939
}
4040

4141
// ... or an`ErrorEvent`, which can provide us with the message but no stack...
42-
if (error.error instanceof ErrorEvent && error.error.message) {
42+
// guarding `ErrorEvent` against `undefined` as it's not defined in Node environments
43+
if (typeof ErrorEvent !== 'undefined' && error.error instanceof ErrorEvent && error.error.message) {
4344
return error.error.message;
4445
}
4546

packages/angular/test/errorhandler.test.ts

+17
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,11 @@ describe('SentryErrorHandler', () => {
4545
});
4646

4747
describe('handleError method', () => {
48+
const originalErrorEvent = globalThis.ErrorEvent;
49+
afterEach(() => {
50+
globalThis.ErrorEvent = originalErrorEvent;
51+
});
52+
4853
it('extracts `null` error', () => {
4954
createErrorHandler().handleError(null);
5055

@@ -223,6 +228,18 @@ describe('SentryErrorHandler', () => {
223228
expect(captureExceptionSpy).toHaveBeenCalledWith('Handled unknown error', captureExceptionEventHint);
224229
});
225230

231+
it('handles ErrorEvent being undefined', () => {
232+
const httpErr = new ErrorEvent('http', { message: 'sentry-http-test' });
233+
const err = new HttpErrorResponse({ error: httpErr });
234+
235+
// @ts-expect-error - this is fine in this test
236+
delete globalThis.ErrorEvent;
237+
238+
expect(() => {
239+
createErrorHandler().handleError(err);
240+
}).not.toThrow();
241+
});
242+
226243
it('extracts an Error with `ngOriginalError`', () => {
227244
const ngErr = new Error('sentry-ng-test');
228245
const err = {

0 commit comments

Comments
 (0)