Skip to content

Commit

Permalink
chore(telemetry/sentry): refine + add comments
Browse files Browse the repository at this point in the history
  • Loading branch information
caugner committed Jan 15, 2025
1 parent ccd904e commit 5e21aa2
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions client/src/telemetry/sentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ import { SENTRY_DSN, SENTRY_ENVIRONMENT, SENTRY_RELEASE } from "../env";

let sentryPromise: Promise<any> | null = null;

/**
* Loads the Sentry module asynchronously and initializes it.
* Utilizes dynamic import to split Sentry related code into a separate chunk.
* Ensures Sentry is only loaded and initialized once.
*
* @returns A promise resolving to the initialized Sentry object.
*/
function loadSentry(): Promise<any> {
if (!sentryPromise) {
sentryPromise = import(
Expand All @@ -15,27 +22,34 @@ function loadSentry(): Promise<any> {
return Sentry;
});
}

return sentryPromise;
}

export function initSentry() {
if (!SENTRY_DSN) {
return;
}
let removeEventListener: (() => void) | null = null;

let onNextError: (() => void) | null = null;
const capturedMessages = new Set<string>();
const errorHandler = (event: ErrorEvent) => {

const handleError = (event: ErrorEvent) => {
loadSentry().then((Sentry) => {
if (removeEventListener) {
removeEventListener();
removeEventListener = null;
if (onNextError) {
onNextError();
onNextError = null;
}
if (!capturedMessages.has(event.message)) {
// Capture every error only once.
Sentry.captureException(event);
capturedMessages.add(event.message);
}
});
};
window.addEventListener("error", errorHandler);
removeEventListener = () => window.removeEventListener("error", errorHandler);

// To avoid capturing too many events, we stop listening after the first error.
onNextError = () => window.removeEventListener("error", handleError);

window.addEventListener("error", handleError);
}

0 comments on commit 5e21aa2

Please sign in to comment.