diff --git a/packages/react-native/Libraries/ReactNative/__tests__/renderApplication-test.js b/packages/react-native/Libraries/ReactNative/__tests__/renderApplication-test.js new file mode 100644 index 00000000000..96933d7e9ff --- /dev/null +++ b/packages/react-native/Libraries/ReactNative/__tests__/renderApplication-test.js @@ -0,0 +1,79 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import type {RenderRootOptions} from '../../Renderer/shims/ReactNativeTypes'; + +import * as ReactNativeFeatureFlags from '../../../src/private/featureflags/ReactNativeFeatureFlags'; +import {dangerouslyResetForTesting} from '../../../src/private/featureflags/ReactNativeFeatureFlagsBase'; +import ExceptionsManager from '../../Core/ExceptionsManager'; +import * as React from 'react'; + +const renderApplication = require('../renderApplication').default; +const render = require('@react-native/jest-preset/jest/renderer'); + +// Use the production container to observe the release surface after an error +jest.mock('../AppContainer', () => jest.requireActual('../AppContainer-prod')); + +// Capture the element and error handlers that `renderApplication` passes to +// Fabric, and render the element with the test renderer instead +const mockFabricRender = jest.fn(); +jest.mock('../../Renderer/shims/ReactFabric', () => ({ + render: mockFabricRender, +})); + +describe('renderApplication', () => { + afterEach(() => { + mockFabricRender.mockClear(); + jest.restoreAllMocks(); + dangerouslyResetForTesting(); + }); + + test('leaves the root View empty and reports a non-fatal error when enabled', async () => { + ReactNativeFeatureFlags.override({enableRootErrorBoundary: () => true}); + const error = new Error('Thrown while rendering'); + const handleException = jest + .spyOn(ExceptionsManager, 'handleException') + .mockImplementation(() => {}); + // Silence React's default caught-error log from the test renderer + jest.spyOn(console, 'error').mockImplementation(() => {}); + + const {element, options} = renderApplicationWithError(error); + const renderer = await render.create(element); + const output = renderer.toJSON(); + await render.unmount(renderer); + // Call the caught-error handler that Fabric receives, because the test + // renderer does not accept error handlers + options.onCaughtError?.(error, {}); + + expect(output).toMatchObject({type: 'View', children: null}); + expect(handleException).toHaveBeenCalledWith(error, false); + }); + + test('leaves the render error uncaught by default', async () => { + const error = new Error('Thrown while rendering'); + const {element} = renderApplicationWithError(error); + + // The test renderer rethrows errors that reach the uncaught error path + await expect(render.create(element)).rejects.toBe(error); + }); +}); + +function renderApplicationWithError(error: Error): { + element: React.MixedElement, + options: RenderRootOptions, +} { + function RootComponent(): React.Node { + throw error; + } + + renderApplication({RootComponent, initialProps: {}, rootTag: 1}); + const [element, , , , options] = mockFabricRender.mock.calls[0]; + return {element, options}; +} diff --git a/packages/react-native/Libraries/ReactNative/renderApplication.js b/packages/react-native/Libraries/ReactNative/renderApplication.js index 6b92a8d4403..469de3a8d9d 100644 --- a/packages/react-native/Libraries/ReactNative/renderApplication.js +++ b/packages/react-native/Libraries/ReactNative/renderApplication.js @@ -11,6 +11,7 @@ import type {ViewStyleProp} from '../StyleSheet/StyleSheet'; import type {RootTag} from './RootTag'; +import {enableRootErrorBoundary} from '../../src/private/featureflags/ReactNativeFeatureFlags'; import AppContainer from './AppContainer'; import DisplayMode, {type DisplayModeType} from './DisplayMode'; import getCachedComponentWithDebugName from './getCachedComponentWithDebugName'; @@ -49,6 +50,7 @@ export default function renderApplication({ }: RenderApplicationOptions) { invariant(rootTag, 'Expect to have a valid rootTag, instead got %s', rootTag); + const rootComponent = ; let renderable: React.MixedElement = ( ({ rootViewStyle={rootViewStyle} initialProps={initialProps ?? Object.freeze({})} internal_excludeLogBox={isLogBox}> - + {enableRootErrorBoundary() ? ( + {rootComponent} + ) : ( + rootComponent + )} ); @@ -90,3 +96,21 @@ export default function renderApplication({ rootTag: createRootTag(rootTag), }); } + +type RootErrorBoundaryState = {hasError: boolean}; + +// React Native reports errors caught here as non-fatal +class RootErrorBoundary extends React.Component< + {children: React.Node}, + RootErrorBoundaryState, +> { + state: RootErrorBoundaryState = {hasError: false}; + + static getDerivedStateFromError(): RootErrorBoundaryState { + return {hasError: true}; + } + + render(): React.Node { + return this.state.hasError ? null : this.props.children; + } +} diff --git a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js index fd7776fac49..361d520ba74 100644 --- a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js +++ b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js @@ -1225,6 +1225,16 @@ const definitions: FeatureFlagDefinitions = { }, ossReleaseStage: 'none', }, + enableRootErrorBoundary: { + defaultValue: false, + metadata: { + description: + 'Leave a surface blank and report a non-fatal error when no app error boundary catches a React error in its root component tree.', + expectedReleaseValue: false, + purpose: 'operational', + }, + ossReleaseStage: 'none', + }, externalElementInspectionEnabled: { defaultValue: true, metadata: { diff --git a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js index ce26327cf2a..9a4a2764dab 100644 --- a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js +++ b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<19928f42843899212bc6ff3bc8a08ba9>> + * @generated SignedSource<> * @flow strict * @noformat */ @@ -35,6 +35,7 @@ export type ReactNativeFeatureFlagsJsOnly = Readonly<{ animatedShouldSyncValueBeforeStartCallback: Getter, deferFlatListFocusChangeRenderUpdate: Getter, delayPressInInScrollView: Getter, + enableRootErrorBoundary: Getter, externalElementInspectionEnabled: Getter, fixCrossOrientationNestedListViewability: Getter, fixVirtualizeListCollapseWindowSize: Getter, @@ -189,6 +190,11 @@ export const deferFlatListFocusChangeRenderUpdate: Getter = createJavaS */ export const delayPressInInScrollView: Getter = createJavaScriptFlagGetter('delayPressInInScrollView', false); +/** + * Leave a surface blank and report a non-fatal error when no app error boundary catches a React error in its root component tree. + */ +export const enableRootErrorBoundary: Getter = createJavaScriptFlagGetter('enableRootErrorBoundary', false); + /** * Enable the external inspection API for DevTools to communicate with the Inspector overlay. */