diff --git a/weave-js/src/common/util/sentry.ts b/weave-js/src/common/util/sentry.ts new file mode 100644 index 00000000000..cb719d399e5 --- /dev/null +++ b/weave-js/src/common/util/sentry.ts @@ -0,0 +1,76 @@ +/** + * Sentry Utilities + * + * This file provides utility functions for reporting errors to Sentry, + * a platform for monitoring and tracking errors in real-time. + * These utilities help streamline the process of capturing and + * sending error information to Sentry for better debugging and + * error management in the application. + * + * Note: These functions rely on the Sentry configuration of the main application. + * The Sentry setup and initialization should be handled in the main application, + * not in this submodule. See frontends/app/src/integrations.ts for the Sentry setup. + * + */ + +import * as Sentry from '@sentry/react'; + +const sentryDedupeSuffix = '[sentry:dedupe]'; + +/** + * Captures an error in Sentry and logs it to the console with a dedupe suffix. + * + * @param error - The error to be captured and logged. Can be a string or an Error object. + * @param tags - Optional. A record of key-value pairs for custom tags to be sent with the error to Sentry. + * @param fingerprint - Optional. An array of strings used to group errors in Sentry. + */ +export function captureAndLogError( + error: string | Error, + tags?: Record, + fingerprint?: string[] +): void { + // Capture the error in Sentry with custom tags and fingerprint + Sentry.captureException(error, { + tags, + fingerprint, + }); + + // Prepare the error message + const errorMessage = error instanceof Error ? error.message : error; + const dedupeMessage = `${errorMessage} ${sentryDedupeSuffix}`; + + // Log the error to the console + console.error(dedupeMessage); +} + +/** + * Captures an error in Sentry and throws it with a dedupe suffix. + * + * @param error - The error to be captured and thrown. Can be a string or an Error object. + * @param tags - Optional. A record of key-value pairs for custom tags to be sent with the error to Sentry. + * @param fingerprint - Optional. An array of strings used to group errors in Sentry. + * @throws {Error} The original error with a dedupe suffix appended to its message. + */ +export function captureAndThrowError( + error: string | Error, + tags?: Record, + fingerprint?: string[] +): never { + // Capture the error in Sentry with custom tags and fingerprint + Sentry.captureException(error, { + tags, + fingerprint, + }); + + // Prepare the error message + const errorMessage = error instanceof Error ? error.message : error; + const dedupeMessage = `${errorMessage} ${sentryDedupeSuffix}`; + + // Throw the error with the dedupe suffix + if (error instanceof Error) { + error.message = dedupeMessage; + throw error; + } else { + throw new Error(dedupeMessage); + } +}