Skip to content

Commit

Permalink
fix(angular): Guard ErrorEvent check in ErrorHandler to avoid throw…
Browse files Browse the repository at this point in the history
…ing in Node environments (#12892)

Add a guard for referencing `ErrorEvent` which is only
available in browser environments but not in Node.
  • Loading branch information
Lms24 authored Jul 12, 2024
1 parent 963eab7 commit 9f07f99
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/angular/src/errorhandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ function extractHttpModuleError(error: HttpErrorResponse): string | Error {
}

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

Expand Down
17 changes: 17 additions & 0 deletions packages/angular/test/errorhandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ describe('SentryErrorHandler', () => {
});

describe('handleError method', () => {
const originalErrorEvent = globalThis.ErrorEvent;
afterEach(() => {
globalThis.ErrorEvent = originalErrorEvent;
});

it('extracts `null` error', () => {
createErrorHandler().handleError(null);

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

it('handles ErrorEvent being undefined', () => {
const httpErr = new ErrorEvent('http', { message: 'sentry-http-test' });
const err = new HttpErrorResponse({ error: httpErr });

// @ts-expect-error - this is fine in this test
delete globalThis.ErrorEvent;

expect(() => {
createErrorHandler().handleError(err);
}).not.toThrow();
});

it('extracts an Error with `ngOriginalError`', () => {
const ngErr = new Error('sentry-ng-test');
const err = {
Expand Down

0 comments on commit 9f07f99

Please sign in to comment.