Skip to content

Commit cf12d40

Browse files
committed
Add an opt-in error boundary around the root component
Apps can enable `enableRootErrorBoundary` at startup to wrap the root component in an error boundary. If a React error reaches that boundary in a release build, the failed surface stays blank until the boundary is remounted, and React Native reports the error as non-fatal. The flag is an operational, per-app policy: both its default value and its expected release value are off, so uncaught React errors stay fatal in every app that does not opt in. `yarn jest --runInBand --runTestsByPath packages/react-native/Libraries/ReactNative/__tests__/renderApplication-test.js` verifies the empty root view, the non-fatal report from the caught-error handler that `renderApplication` passes to Fabric, and the default uncaught path. Each assertion fails when its behavior is removed. The remaining `Libraries/ReactNative` Jest tests, `yarn flow-check`, `yarn lint`, and `yarn format-check-javascript` pass. `yarn featureflags --update` leaves the generated files unchanged. Signed-off-by: James Ide <ide@expo.dev>
1 parent 37beffc commit cf12d40

4 files changed

Lines changed: 121 additions & 2 deletions

File tree

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @flow strict-local
8+
* @format
9+
*/
10+
11+
import type {RenderRootOptions} from '../../Renderer/shims/ReactNativeTypes';
12+
13+
import * as ReactNativeFeatureFlags from '../../../src/private/featureflags/ReactNativeFeatureFlags';
14+
import {dangerouslyResetForTesting} from '../../../src/private/featureflags/ReactNativeFeatureFlagsBase';
15+
import ExceptionsManager from '../../Core/ExceptionsManager';
16+
import * as React from 'react';
17+
18+
const renderApplication = require('../renderApplication').default;
19+
const render = require('@react-native/jest-preset/jest/renderer');
20+
21+
// Use the production container to observe the release surface after an error
22+
jest.mock('../AppContainer', () => jest.requireActual('../AppContainer-prod'));
23+
24+
// Capture the element and error handlers that `renderApplication` passes to
25+
// Fabric, and render the element with the test renderer instead
26+
const mockFabricRender = jest.fn();
27+
jest.mock('../../Renderer/shims/ReactFabric', () => ({
28+
render: mockFabricRender,
29+
}));
30+
31+
describe('renderApplication', () => {
32+
afterEach(() => {
33+
mockFabricRender.mockClear();
34+
jest.restoreAllMocks();
35+
dangerouslyResetForTesting();
36+
});
37+
38+
test('leaves the root View empty and reports a non-fatal error when enabled', async () => {
39+
ReactNativeFeatureFlags.override({enableRootErrorBoundary: () => true});
40+
const error = new Error('Thrown while rendering');
41+
const handleException = jest
42+
.spyOn(ExceptionsManager, 'handleException')
43+
.mockImplementation(() => {});
44+
// Silence React's default caught-error log from the test renderer
45+
jest.spyOn(console, 'error').mockImplementation(() => {});
46+
47+
const {element, options} = renderApplicationWithError(error);
48+
const renderer = await render.create(element);
49+
const output = renderer.toJSON();
50+
await render.unmount(renderer);
51+
// Call the caught-error handler that Fabric receives, because the test
52+
// renderer does not accept error handlers
53+
options.onCaughtError?.(error, {});
54+
55+
expect(output).toMatchObject({type: 'View', children: null});
56+
expect(handleException).toHaveBeenCalledWith(error, false);
57+
});
58+
59+
test('leaves the render error uncaught by default', async () => {
60+
const error = new Error('Thrown while rendering');
61+
const {element} = renderApplicationWithError(error);
62+
63+
// The test renderer rethrows errors that reach the uncaught error path
64+
await expect(render.create(element)).rejects.toBe(error);
65+
});
66+
});
67+
68+
function renderApplicationWithError(error: Error): {
69+
element: React.MixedElement,
70+
options: RenderRootOptions,
71+
} {
72+
function RootComponent(): React.Node {
73+
throw error;
74+
}
75+
76+
renderApplication({RootComponent, initialProps: {}, rootTag: 1});
77+
const [element, , , , options] = mockFabricRender.mock.calls[0];
78+
return {element, options};
79+
}

‎packages/react-native/Libraries/ReactNative/renderApplication.js‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import type {ViewStyleProp} from '../StyleSheet/StyleSheet';
1212
import type {RootTag} from './RootTag';
1313

14+
import {enableRootErrorBoundary} from '../../src/private/featureflags/ReactNativeFeatureFlags';
1415
import AppContainer from './AppContainer';
1516
import DisplayMode, {type DisplayModeType} from './DisplayMode';
1617
import getCachedComponentWithDebugName from './getCachedComponentWithDebugName';
@@ -49,14 +50,19 @@ export default function renderApplication<Props extends {...}>({
4950
}: RenderApplicationOptions<Props>) {
5051
invariant(rootTag, 'Expect to have a valid rootTag, instead got %s', rootTag);
5152

53+
const rootComponent = <RootComponent {...initialProps} rootTag={rootTag} />;
5254
let renderable: React.MixedElement = (
5355
<AppContainer
5456
rootTag={rootTag}
5557
WrapperComponent={WrapperComponent}
5658
rootViewStyle={rootViewStyle}
5759
initialProps={initialProps ?? Object.freeze({})}
5860
internal_excludeLogBox={isLogBox}>
59-
<RootComponent {...initialProps} rootTag={rootTag} />
61+
{enableRootErrorBoundary() ? (
62+
<RootErrorBoundary>{rootComponent}</RootErrorBoundary>
63+
) : (
64+
rootComponent
65+
)}
6066
</AppContainer>
6167
);
6268

@@ -90,3 +96,21 @@ export default function renderApplication<Props extends {...}>({
9096
rootTag: createRootTag(rootTag),
9197
});
9298
}
99+
100+
type RootErrorBoundaryState = {hasError: boolean};
101+
102+
// React Native reports errors caught here as non-fatal
103+
class RootErrorBoundary extends React.Component<
104+
{children: React.Node},
105+
RootErrorBoundaryState,
106+
> {
107+
state: RootErrorBoundaryState = {hasError: false};
108+
109+
static getDerivedStateFromError(): RootErrorBoundaryState {
110+
return {hasError: true};
111+
}
112+
113+
render(): React.Node {
114+
return this.state.hasError ? null : this.props.children;
115+
}
116+
}

‎packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1225,6 +1225,16 @@ const definitions: FeatureFlagDefinitions = {
12251225
},
12261226
ossReleaseStage: 'none',
12271227
},
1228+
enableRootErrorBoundary: {
1229+
defaultValue: false,
1230+
metadata: {
1231+
description:
1232+
'Leave a surface blank and report a non-fatal error when no app error boundary catches a React error in its root component tree.',
1233+
expectedReleaseValue: false,
1234+
purpose: 'operational',
1235+
},
1236+
ossReleaseStage: 'none',
1237+
},
12281238
externalElementInspectionEnabled: {
12291239
defaultValue: true,
12301240
metadata: {

‎packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
66
*
7-
* @generated SignedSource<<19928f42843899212bc6ff3bc8a08ba9>>
7+
* @generated SignedSource<<a6ddf958fd79ee279f5a85b44f44a7e8>>
88
* @flow strict
99
* @noformat
1010
*/
@@ -35,6 +35,7 @@ export type ReactNativeFeatureFlagsJsOnly = Readonly<{
3535
animatedShouldSyncValueBeforeStartCallback: Getter<boolean>,
3636
deferFlatListFocusChangeRenderUpdate: Getter<boolean>,
3737
delayPressInInScrollView: Getter<boolean>,
38+
enableRootErrorBoundary: Getter<boolean>,
3839
externalElementInspectionEnabled: Getter<boolean>,
3940
fixCrossOrientationNestedListViewability: Getter<boolean>,
4041
fixVirtualizeListCollapseWindowSize: Getter<boolean>,
@@ -189,6 +190,11 @@ export const deferFlatListFocusChangeRenderUpdate: Getter<boolean> = createJavaS
189190
*/
190191
export const delayPressInInScrollView: Getter<boolean> = createJavaScriptFlagGetter('delayPressInInScrollView', false);
191192

193+
/**
194+
* Leave a surface blank and report a non-fatal error when no app error boundary catches a React error in its root component tree.
195+
*/
196+
export const enableRootErrorBoundary: Getter<boolean> = createJavaScriptFlagGetter('enableRootErrorBoundary', false);
197+
192198
/**
193199
* Enable the external inspection API for DevTools to communicate with the Inspector overlay.
194200
*/

0 commit comments

Comments
 (0)