Repository navigation
fix(react-native): capture fatal React render errors #5293
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
922eca4
fix(react-native): capture fatal React render errors
turnipdabeets 04df8ff
fix(react-native): capture a repeated fatal after its duplicate is pa…
turnipdabeets c819d3b
chore: describe the render-error capture as a fix in the changeset
turnipdabeets 6b29619
fix(react-native): dedupe each in-flight fatal and hold its duplicate…
turnipdabeets 9df50c6
fix(react-native): capture a fatal once when the previous handler for…
turnipdabeets fc1cd01
Merge branch 'main' into fix/rn-render-error-capture
turnipdabeets 8611ecf
fix(react-native): keep ExceptionsManager out of web bundles
turnipdabeets 0844a71
Merge remote-tracking branch 'origin/fix/rn-render-error-capture' int…
turnipdabeets File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| 'posthog-react-native': patch | ||
| --- | ||
|
|
||
| Fix React render errors that crash the app not being captured on React Native 0.78 and newer when `errorTracking.autocapture.uncaughtExceptions` is enabled. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
packages/react-native/src/optional/OptionalReactNativeExceptionsManager.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| import { Platform } from 'react-native' | ||
|
|
||
| // React Native's internal exception reporter. React 19's root `onUncaughtError` and | ||
| // `onCaughtError` callbacks report through `handleException` without going through ErrorUtils. | ||
| // Callers read `handleException` off this object at call time, so it can be wrapped in place. | ||
| export type ReactNativeExceptionsManager = { | ||
| handleException?: (error: unknown, isFatal: boolean) => void | ||
| } | ||
|
|
||
| export let OptionalReactNativeExceptionsManager: ReactNativeExceptionsManager | undefined | ||
|
|
||
| if (Platform.OS !== 'web') { | ||
| try { | ||
| // Metro recognizes optional dependencies only when require is directly inside the try block. | ||
| const exceptionsManager = require('react-native/Libraries/Core/ExceptionsManager') | ||
|
turnipdabeets marked this conversation as resolved.
Resolved
|
||
| // CommonJS `module.exports` up to RN 0.78, an ES default export from 0.79. | ||
| OptionalReactNativeExceptionsManager = exceptionsManager?.default ?? exceptionsManager | ||
| } catch {} | ||
| } | ||
5 changes: 5 additions & 0 deletions
5
packages/react-native/src/optional/OptionalReactNativeExceptionsManager.web.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| import type { ReactNativeExceptionsManager } from './OptionalReactNativeExceptionsManager' | ||
|
|
||
| // Web bundles resolve this file instead, so React Native's ExceptionsManager and its native-only | ||
| // imports stay out of the web dependency graph. | ||
| export const OptionalReactNativeExceptionsManager: ReactNativeExceptionsManager | undefined = undefined |
90 changes: 90 additions & 0 deletions
90
packages/react-native/test/optional-exceptions-manager.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import { execFileSync } from 'child_process' | ||
| import { mkdtempSync, mkdirSync, copyFileSync, writeFileSync, rmSync, readFileSync, realpathSync } from 'fs' | ||
| import { createRequire } from 'module' | ||
| import { tmpdir } from 'os' | ||
| import { join, resolve } from 'path' | ||
|
|
||
| const LOADER = resolve(__dirname, '../dist/optional/OptionalReactNativeExceptionsManager.js') | ||
| const WEB_LOADER = resolve(__dirname, '../dist/optional/OptionalReactNativeExceptionsManager.web.js') | ||
|
|
||
| const metroDependencies = (file: string): { name: string; data: { isOptional?: boolean } }[] => { | ||
| // Resolve from Metro's real location so pnpm's transitive Babel dependency is available. | ||
| const metroRequire = createRequire(realpathSync(resolve(__dirname, '../node_modules/metro/package.json'))) | ||
| const parser = metroRequire('@babel/parser') | ||
| const collectDependencies = metroRequire('./src/ModuleGraph/worker/collectDependencies.js') | ||
| return collectDependencies(parser.parse(readFileSync(file, 'utf8')), { | ||
| asyncRequireModulePath: 'metro-runtime/src/modules/asyncRequire', | ||
| dynamicRequires: 'reject', | ||
| inlineableCalls: [], | ||
| keepRequireNames: true, | ||
| allowOptionalDependencies: true, | ||
| unstable_allowRequireContext: false, | ||
| }).dependencies | ||
| } | ||
|
|
||
| // test:unit depends on build in Turbo. Exercise the emitted loader with Node's actual require | ||
| // resolution, outside Vitest's module mocks. | ||
| const loadExceptionsManager = (platform: string, moduleSource?: string): unknown => { | ||
| const directory = mkdtempSync(join(tmpdir(), 'posthog-optional-exceptions-manager-')) | ||
| try { | ||
| copyFileSync(LOADER, join(directory, 'loader.cjs')) | ||
| const nativeDirectory = join(directory, 'node_modules/react-native') | ||
| mkdirSync(join(nativeDirectory, 'Libraries/Core'), { recursive: true }) | ||
| writeFileSync(join(nativeDirectory, 'index.js'), `exports.Platform = { OS: ${JSON.stringify(platform)} }`) | ||
| if (moduleSource !== undefined) { | ||
| writeFileSync(join(nativeDirectory, 'Libraries/Core/ExceptionsManager.js'), moduleSource) | ||
| } | ||
| return JSON.parse( | ||
| execFileSync( | ||
| process.execPath, | ||
| [ | ||
| '-e', | ||
| "const m = require('./loader.cjs').OptionalReactNativeExceptionsManager; console.log(JSON.stringify({ handleException: typeof m?.handleException, loaded: global.loaded === true }))", | ||
| ], | ||
| { cwd: directory, encoding: 'utf8' } | ||
| ) | ||
| ) | ||
| } finally { | ||
| rmSync(directory, { recursive: true, force: true }) | ||
| } | ||
| } | ||
|
|
||
| describe('OptionalReactNativeExceptionsManager built loader', () => { | ||
| it('marks the ExceptionsManager deep import as optional in the emitted Metro dependency graph', () => { | ||
| expect(metroDependencies(LOADER)).toEqual( | ||
| expect.arrayContaining([ | ||
| expect.objectContaining({ | ||
| name: 'react-native/Libraries/Core/ExceptionsManager', | ||
| data: expect.objectContaining({ isOptional: true }), | ||
| }), | ||
| ]) | ||
| ) | ||
| }) | ||
|
|
||
| it('keeps React Native out of the web loader dependency graph', () => { | ||
| // React Native 0.79 and older have no web implementation of the modules ExceptionsManager | ||
| // imports, so web bundling fails if Metro reaches it. | ||
| expect(metroDependencies(WEB_LOADER)).toEqual([]) | ||
| }) | ||
|
|
||
| it.each([ | ||
| ['CommonJS exports (RN 0.78 and older)', 'global.loaded = true; module.exports = { handleException() {} }'], | ||
| [ | ||
| 'an ES default export (RN 0.79 and newer)', | ||
| 'global.loaded = true; exports.__esModule = true; exports.default = { handleException() {} }', | ||
| ], | ||
| ])('resolves handleException from %s', (_, source) => { | ||
| expect(loadExceptionsManager('ios', source)).toEqual({ loaded: true, handleException: 'function' }) | ||
| }) | ||
|
|
||
| it('tolerates a missing module', () => { | ||
| expect(loadExceptionsManager('android')).toEqual({ loaded: false, handleException: 'undefined' }) | ||
| }) | ||
|
|
||
| it('does not load the module on web', () => { | ||
| expect(loadExceptionsManager('web', 'global.loaded = true; module.exports = { handleException() {} }')).toEqual({ | ||
| loaded: false, | ||
| handleException: 'undefined', | ||
| }) | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.