diff --git a/CHANGELOG.md b/CHANGELOG.md index 843ba5cad0..3e44ede39a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ ### Fixes +- Capture render errors that no error boundary catches as fatal crashes on React Native 0.78+ ([#7078](https://github.com/getsentry/sentry-react-native/pull/7078)) + - React 19 reports these errors directly to React Native's `ExceptionsManager` and skips `ErrorUtils`, so before this fix the SDK lost them on Android and iOS. - Remove the web Session Replay and User Feedback packages from Android and iOS bundles by default, as announced in 5.32.0 ([#7062](https://github.com/getsentry/sentry-react-native/pull/7062)) - Before this fix, `includeWebReplay` and `includeWebFeedback` defaulted to `true`, so these packages stayed in native bundles even though they never run there. - Web bundles keep both packages. Set the option to `true` to keep a package on all platforms, or to `false` to remove it on all platforms, including web. diff --git a/packages/core/src/js/integrations/reactnativeerrorhandlers.ts b/packages/core/src/js/integrations/reactnativeerrorhandlers.ts index 6f272d4509..2df8e35835 100644 --- a/packages/core/src/js/integrations/reactnativeerrorhandlers.ts +++ b/packages/core/src/js/integrations/reactnativeerrorhandlers.ts @@ -13,6 +13,7 @@ import type { ReactNativeClientOptions } from '../options'; import { isHermesEnabled, isWeb } from '../utils/environment'; import { createSyntheticError, isErrorLike } from '../utils/error'; +import { ReactNativeLibraries } from '../utils/rnlibraries'; import { RN_GLOBAL_OBJ } from '../utils/worldwide'; import { hasInterestedSubscribers, publishGlobalError } from './globalErrorBus'; import { checkPromiseAndWarn, polyfillPromise, requireRejectionTracking } from './reactnativeerrorhandlersutils'; @@ -148,6 +149,8 @@ function attachUnhandledRejectionHandler(): void { function setupErrorUtilsGlobalHandler(): void { let handlingFatal = false; + let forwarding = false; + const forwardedFatals = new WeakSet(); const errorUtils = RN_GLOBAL_OBJ.ErrorUtils; if (!errorUtils) { @@ -158,8 +161,21 @@ function setupErrorUtilsGlobalHandler(): void { // oxlint-disable-next-line typescript-eslint(no-unsafe-member-access) const defaultHandler = errorUtils.getGlobalHandler?.(); - // oxlint-disable-next-line typescript-eslint(no-explicit-any), typescript-eslint(no-unsafe-member-access) - errorUtils.setGlobalHandler(async (error: any, isFatal?: boolean) => { + // The default handler reports the error through ExceptionsManager.handleException, which must not capture it again. + const forward = (error: unknown, isFatal: boolean | undefined, report: () => void): void => { + if (isFatal && typeof error === 'object' && error !== null) { + forwardedFatals.add(error); + } + forwarding = true; + try { + report(); + } finally { + forwarding = false; + } + }; + + // oxlint-disable-next-line typescript-eslint(no-explicit-any) + const handleError = async (error: any, isFatal: boolean | undefined, report: () => void): Promise => { // We want to handle fatals, but only in production mode. const shouldHandleFatal = isFatal && !__DEV__; if (shouldHandleFatal) { @@ -176,7 +192,7 @@ function setupErrorUtilsGlobalHandler(): void { debug.error('Sentry client is missing, the error event might be lost.', error); // If there is no client something is fishy, anyway we call the default handler - defaultHandler(error, isFatal); + forward(error, isFatal, report); return; } @@ -228,7 +244,7 @@ function setupErrorUtilsGlobalHandler(): void { // If in dev, we call the default handler anyway and hope the error will be sent // Just for a better dev experience. If a fallback is mounted it will still // render alongside LogBox. - defaultHandler(error, isFatal); + forward(error, isFatal, report); return; } @@ -240,7 +256,7 @@ function setupErrorUtilsGlobalHandler(): void { // If a fallback will render, we skip the default handler so it can own // the screen instead of being torn down. if (!hasInterestedSubscribers('onerror', !!isFatal)) { - defaultHandler(error, isFatal); + forward(error, isFatal, report); } // Release the latch so any subsequent fatal can still be captured. // Before GlobalErrorBoundary existed, the default handler always tore @@ -260,7 +276,30 @@ function setupErrorUtilsGlobalHandler(): void { } }, ); - }); + }; + + // oxlint-disable-next-line typescript-eslint(no-explicit-any), typescript-eslint(no-unsafe-member-access) + errorUtils.setGlobalHandler((error: any, isFatal?: boolean) => + handleError(error, isFatal, () => defaultHandler(error, isFatal)), + ); + + // Since React 19 (React Native 0.78), a render error that no error boundary catches skips ErrorUtils. + // The root onUncaughtError callback reports it directly to ExceptionsManager.handleException as a fatal. + const exceptionsManager = ReactNativeLibraries.ExceptionsManager; + const handleException = exceptionsManager?.handleException; + if (exceptionsManager && handleException) { + exceptionsManager.handleException = (error: unknown, isFatal: boolean): void => { + const report = (): void => handleException.call(exceptionsManager, error, isFatal); + const forwarded = forwarding || (typeof error === 'object' && error !== null && forwardedFatals.has(error)); + if (!isFatal || forwarded) { + report(); + return; + } + handleError(error, isFatal, report).catch((e: unknown) => { + debug.error('[ReactNativeErrorHandlers] Failed to handle the fatal error.', e); + }); + }; + } } /** diff --git a/packages/core/src/js/utils/rnlibraries.ts b/packages/core/src/js/utils/rnlibraries.ts index afef515493..59791d8737 100644 --- a/packages/core/src/js/utils/rnlibraries.ts +++ b/packages/core/src/js/utils/rnlibraries.ts @@ -46,6 +46,10 @@ const InternalReactNativeLibrariesInterface: Required(name: string, getValue: () => T): void => { diff --git a/packages/core/src/js/utils/rnlibrariesinterface.ts b/packages/core/src/js/utils/rnlibrariesinterface.ts index 3a8e4446f8..cf4e0ea1ba 100644 --- a/packages/core/src/js/utils/rnlibrariesinterface.ts +++ b/packages/core/src/js/utils/rnlibrariesinterface.ts @@ -24,6 +24,7 @@ export interface ReactNativeLibrariesInterface { Utilities?: { polyfillGlobal: (name: string, getValue: () => T) => void; }; + ExceptionsManager?: ReactNative.ExceptionsManager; Promise?: typeof Promise; ReactNativeVersion?: ReactNative.ReactNativeVersion; TurboModuleRegistry?: ReactNative.TurboModuleRegistry; diff --git a/packages/core/src/js/vendor/react-native/index.ts b/packages/core/src/js/vendor/react-native/index.ts index 8b5cf00420..d1b35efb58 100644 --- a/packages/core/src/js/vendor/react-native/index.ts +++ b/packages/core/src/js/vendor/react-native/index.ts @@ -83,6 +83,11 @@ export type ReactNativeVersion = { }; }; +// Adapted from https://github.com/facebook/react-native/blob/bbfd391496baa6e0461262f76f1ae9a819a7ecd2/packages/react-native/Libraries/Core/ExceptionsManager.js#L151 +export type ExceptionsManager = { + handleException: (error: unknown, isFatal: boolean) => void; +}; + export type AppRegistry = { // oxlint-disable-next-line typescript-eslint(no-explicit-any) runApplication: (appKey: string, appParameters: any) => void; diff --git a/packages/core/test/integrations/reactnativeerrorhandlers.test.ts b/packages/core/test/integrations/reactnativeerrorhandlers.test.ts index c2f08a68fa..d6f59b8e30 100644 --- a/packages/core/test/integrations/reactnativeerrorhandlers.test.ts +++ b/packages/core/test/integrations/reactnativeerrorhandlers.test.ts @@ -37,6 +37,16 @@ jest.mock('../../src/js/utils/worldwide', () => { }; }); +const mockExceptionsManager: { handleException?: (error: unknown, isFatal: boolean) => void } = {}; + +jest.mock('../../src/js/utils/rnlibraries', () => ({ + ReactNativeLibraries: { + get ExceptionsManager() { + return mockExceptionsManager; + }, + }, +})); + jest.mock('@sentry/core', () => { const actual = jest.requireActual('@sentry/core'); return { @@ -294,6 +304,81 @@ describe('ReactNativeErrorHandlers', () => { expect(defaultHandler).toHaveBeenCalledTimes(1); }); }); + + describe('ExceptionsManager.handleException', () => { + let handleException: jest.Mock; + + beforeEach(() => { + handleException = jest.fn(); + mockExceptionsManager.handleException = handleException; + // React Native's default global handler reports through ExceptionsManager. + (RN_GLOBAL_OBJ.ErrorUtils!.getGlobalHandler as jest.Mock).mockReturnValue( + jest.fn((error: unknown, isFatal?: boolean) => mockExceptionsManager.handleException!(error, !!isFatal)), + ); + set__DEV__(false); + }); + + afterEach(() => { + set__DEV__(true); + }); + + it('captures a fatal render error and reports it to React Native after the flush', async () => { + const integration = reactNativeErrorHandlersIntegration(); + integration.setupOnce!(); + const error = new Error('Render error'); + + mockExceptionsManager.handleException!(error, true); + + expect(handleException).not.toHaveBeenCalled(); + await flushPromises(client); + expect(client.eventQueue).toHaveLength(1); + expect(client.event?.level).toBe('fatal' as SeverityLevel); + expect(client.event?.exception?.values?.[0]?.mechanism).toEqual({ handled: false, type: 'onerror' }); + expect(handleException.mock.calls).toEqual([[error, true]]); + }); + + it('passes an error caught by an error boundary through without capturing it', async () => { + const integration = reactNativeErrorHandlersIntegration(); + integration.setupOnce!(); + const error = new Error('Caught render error'); + + mockExceptionsManager.handleException!(error, false); + await flushPromises(client); + + expect(client.eventQueue).toHaveLength(0); + expect(handleException.mock.calls).toEqual([[error, false]]); + }); + + it.each([ + ['an error', new Error('Handler error')], + ['a string', 'Handler error'], + ])('captures %s once when the default handler reports it through ExceptionsManager', async (_, error) => { + const integration = reactNativeErrorHandlersIntegration(); + integration.setupOnce!(); + + await errorHandlerCallback!(error as Error, true); + await flushPromises(client); + + expect(client.eventQueue).toHaveLength(1); + expect(handleException.mock.calls).toEqual([[error, true]]); + }); + + it('does not capture a fatal again when the previous handler reports it to React Native later', async () => { + const previousHandler = jest.fn(); + (RN_GLOBAL_OBJ.ErrorUtils!.getGlobalHandler as jest.Mock).mockReturnValue(previousHandler); + const integration = reactNativeErrorHandlersIntegration(); + integration.setupOnce!(); + const error = new Error('Handler error'); + + await errorHandlerCallback!(error, true); + await flushPromises(client); + mockExceptionsManager.handleException!(error, true); + + expect(previousHandler).toHaveBeenCalledTimes(1); + expect(client.eventQueue).toHaveLength(1); + expect(handleException.mock.calls).toEqual([[error, true]]); + }); + }); }); describe('onUnhandledRejection', () => { @@ -505,6 +590,12 @@ describe('ReactNativeErrorHandlers', () => { }); }); +async function flushPromises(client: TestClient): Promise { + await new Promise(resolve => setImmediate(resolve)); + await client.flush(); + await new Promise(resolve => setImmediate(resolve)); +} + function set__DEV__(value: boolean): void { Object.defineProperty(globalThis, '__DEV__', { value, writable: true, configurable: true }); }