import * as Sentry from '@sentry/react' import type { ErrorInfo } from 'react' import { getChunkLoadReloadDecision, isChunkLoadError } from '@/lib/chunk-load-error' import { IS_STAGING_OR_PREVIEW } from '@/lib/constants' import { sendFrontendMetric } from '@/lib/frontend-metrics' const countedErrors = new WeakSet() /** * Counts one `global_crash` metric per caught error. Call it only for crashes * that reach the crash screen, not for ones recovered by an automatic reload. */ export function reportGlobalCrashMetric(error: unknown) { if (!IS_STAGING_OR_PREVIEW) return try { if (typeof error === 'object' && error !== null) { if (countedErrors.has(error)) return countedErrors.add(error) } sendFrontendMetric('global_crash') } catch { // Never let metrics break the error handler } } export const errorBoundaryHandler = (error: Error, _info: ErrorInfo) => { // A chunk failure a reload recovers from isn't worth reporting; one that // recurs inside the reload guard window is reported below if (getChunkLoadReloadDecision(error)) { window.location.reload() return } Sentry.withScope(function (scope) { scope.setTag('globalErrorBoundary', true) if (isChunkLoadError(error)) scope.setTag('chunkLoadError', true) const eventId = Sentry.captureException(error) // Attach the Sentry event ID to the error object so it can be accessed by the error boundary if (eventId && error && typeof error === 'object') { ;(error as Error & { sentryId?: string }).sentryId = eventId } }) reportGlobalCrashMetric(error) console.error(error.stack) }