Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
51 changes: 45 additions & 6 deletions packages/core/src/js/integrations/reactnativeerrorhandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@

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';

Check warning on line 19 in packages/core/src/js/integrations/reactnativeerrorhandlers.ts

View check run for this annotation

@sentry/warden / warden: code-review

A rejected fatal-event flush prevents React Native from handling the crash

When a fatal reaches the wrapper with no interested GlobalErrorBoundary and `client.flush()` rejects, the original React Native `ExceptionsManager.handleException` is never called; the rejection branch only logs and resets the latch. Ensure the fatal is reported to React Native when Sentry handling fails.
Comment on lines +16 to 19

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A rejected fatal-event flush prevents React Native from handling the crash

When a fatal reaches the wrapper with no interested GlobalErrorBoundary and client.flush() rejects, the original React Native ExceptionsManager.handleException is never called; the rejection branch only logs and resets the latch. Ensure the fatal is reported to React Native when Sentry handling fails.

Evidence
  • The new ExceptionsManager.handleException wrapper passes fatal errors to handleError with report as the callback for invoking React Native’s original handler.
  • In production, handleError calls report from the flush fulfillment path when no interested boundary exists; its flush rejection handler only logs and resets handlingFatal.
  • Therefore, if the flush rejects for a fatal with no interested boundary, the original handler is skipped. The test for the normal path expects it to be called after the flush resolves.

Identified by Warden · code-review · UGK-TYK

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks valid but probably an edge case 🤔


const INTEGRATION_NAME = 'ReactNativeErrorHandlers';

Expand Down Expand Up @@ -148,6 +149,8 @@

function setupErrorUtilsGlobalHandler(): void {
let handlingFatal = false;
let forwarding = false;
const forwardedFatals = new WeakSet<object>();

const errorUtils = RN_GLOBAL_OBJ.ErrorUtils;
if (!errorUtils) {
Expand All @@ -158,8 +161,21 @@
// 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<void> => {
// We want to handle fatals, but only in production mode.
const shouldHandleFatal = isFatal && !__DEV__;
if (shouldHandleFatal) {
Expand All @@ -176,7 +192,7 @@
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;
}
Expand Down Expand Up @@ -228,7 +244,7 @@
// 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;
}

Expand All @@ -240,7 +256,7 @@
// 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
Expand All @@ -260,7 +276,30 @@
}
},
);
});
};

// 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 => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m: Could we use a fillTyped like

fillTyped(AppRegistry, 'runApplication', originalRunApplication => {

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);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Failed fatals skip native reporting

Medium Severity

The new ExceptionsManager.handleException wrapper intercepts fatals and only calls the original handler through report(). If handleError rejects, the .catch() logs and returns, so React Native never sees the exception. A render error that this change intercepts is then dropped: no Sentry event, no native crash, and a broken tree left on screen.

Additional Locations (1)
Fix in Cursor Fix in Web

Triggered by project rule: PR Review Guidelines for Cursor Bot

Reviewed by Cursor Bugbot for commit 2f5fd5a. Configure here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

};
}
}

/**
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/js/utils/rnlibraries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ const InternalReactNativeLibrariesInterface: Required<ReactNativeLibrariesInterf
return getDevServer();
},
},
// Starting with react-native 0.79, the ExceptionsManager is a default export
ExceptionsManager:
require('react-native/Libraries/Core/ExceptionsManager').default ??
require('react-native/Libraries/Core/ExceptionsManager'),
Promise: require('react-native/Libraries/Promise'),
Utilities: {
polyfillGlobal: <T>(name: string, getValue: () => T): void => {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/js/utils/rnlibrariesinterface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export interface ReactNativeLibrariesInterface {
Utilities?: {
polyfillGlobal: <T>(name: string, getValue: () => T) => void;
};
ExceptionsManager?: ReactNative.ExceptionsManager;
Promise?: typeof Promise;
ReactNativeVersion?: ReactNative.ReactNativeVersion;
TurboModuleRegistry?: ReactNative.TurboModuleRegistry;
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/js/vendor/react-native/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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', () => {
Expand Down Expand Up @@ -505,6 +590,12 @@ describe('ReactNativeErrorHandlers', () => {
});
});

async function flushPromises(client: TestClient): Promise<void> {
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 });
}
Loading