Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -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};
}
26 changes: 25 additions & 1 deletion packages/react-native/Libraries/ReactNative/renderApplication.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -49,14 +50,19 @@ export default function renderApplication<Props extends {...}>({
}: RenderApplicationOptions<Props>) {
invariant(rootTag, 'Expect to have a valid rootTag, instead got %s', rootTag);

const rootComponent = <RootComponent {...initialProps} rootTag={rootTag} />;
let renderable: React.MixedElement = (
<AppContainer
rootTag={rootTag}
WrapperComponent={WrapperComponent}
rootViewStyle={rootViewStyle}
initialProps={initialProps ?? Object.freeze({})}
internal_excludeLogBox={isLogBox}>
<RootComponent {...initialProps} rootTag={rootTag} />
{enableRootErrorBoundary() ? (
<RootErrorBoundary>{rootComponent}</RootErrorBoundary>
) : (
rootComponent
)}
</AppContainer>
);

Expand Down Expand Up @@ -90,3 +96,21 @@ export default function renderApplication<Props extends {...}>({
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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<<a6ddf958fd79ee279f5a85b44f44a7e8>>
* @flow strict
* @noformat
*/
Expand Down Expand Up @@ -35,6 +35,7 @@ export type ReactNativeFeatureFlagsJsOnly = Readonly<{
animatedShouldSyncValueBeforeStartCallback: Getter<boolean>,
deferFlatListFocusChangeRenderUpdate: Getter<boolean>,
delayPressInInScrollView: Getter<boolean>,
enableRootErrorBoundary: Getter<boolean>,
externalElementInspectionEnabled: Getter<boolean>,
fixCrossOrientationNestedListViewability: Getter<boolean>,
fixVirtualizeListCollapseWindowSize: Getter<boolean>,
Expand Down Expand Up @@ -189,6 +190,11 @@ export const deferFlatListFocusChangeRenderUpdate: Getter<boolean> = createJavaS
*/
export const delayPressInInScrollView: Getter<boolean> = 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<boolean> = createJavaScriptFlagGetter('enableRootErrorBoundary', false);

/**
* Enable the external inspection API for DevTools to communicate with the Inspector overlay.
*/
Expand Down
Loading