Skip to content

Commit 1c1690e

Browse files
committed
fix(angular): remove afterSendEvent listener once root injector is destroyed
In this commit, we added cleanup logic to handle the removal of `afterSendEvent`, which is set up within the Angular error handler. This fixes memory leaks that occur when the event is still being handled after the root view is removed.
1 parent a2dcb28 commit 1c1690e

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

packages/angular/src/errorhandler.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { HttpErrorResponse } from '@angular/common/http';
2-
import type { ErrorHandler as AngularErrorHandler } from '@angular/core';
2+
import type { ErrorHandler as AngularErrorHandler, OnDestroy } from '@angular/core';
33
import { Inject, Injectable } from '@angular/core';
44
import * as Sentry from '@sentry/browser';
55
import type { ReportDialogOptions } from '@sentry/browser';
@@ -80,12 +80,14 @@ function isErrorOrErrorLikeObject(value: unknown): value is Error {
8080
* Implementation of Angular's ErrorHandler provider that can be used as a drop-in replacement for the stock one.
8181
*/
8282
@Injectable({ providedIn: 'root' })
83-
class SentryErrorHandler implements AngularErrorHandler {
83+
class SentryErrorHandler implements AngularErrorHandler, OnDestroy {
8484
protected readonly _options: ErrorHandlerOptions;
8585

8686
/* indicates if we already registered our the afterSendEvent handler */
8787
private _registeredAfterSendEventHandler;
8888

89+
private _removeAfterSendEventListener: VoidFunction | null = null;
90+
8991
public constructor(@Inject('errorHandlerOptions') options?: ErrorHandlerOptions) {
9092
this._registeredAfterSendEventHandler = false;
9193

@@ -95,6 +97,12 @@ class SentryErrorHandler implements AngularErrorHandler {
9597
};
9698
}
9799

100+
public ngOnDestroy(): void {
101+
if (this._removeAfterSendEventListener) {
102+
this._removeAfterSendEventListener();
103+
}
104+
}
105+
98106
/**
99107
* Method called for every value captured through the ErrorHandler
100108
*/
@@ -119,7 +127,7 @@ class SentryErrorHandler implements AngularErrorHandler {
119127
const client = Sentry.getClient();
120128

121129
if (client && !this._registeredAfterSendEventHandler) {
122-
client.on('afterSendEvent', (event: Event) => {
130+
this._removeAfterSendEventListener = client.on('afterSendEvent', (event: Event) => {
123131
if (!event.type && event.event_id) {
124132
runOutsideAngular(() => {
125133
Sentry.showReportDialog({ ...this._options.dialogOptions, eventId: event.event_id! });

0 commit comments

Comments
 (0)