Skip to content
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

Disable prepareStackTrace while we're generating stacks #18708

Merged
merged 1 commit into from Apr 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -1672,6 +1672,62 @@ describe('ReactIncrementalErrorHandling', () => {
expect(ReactNoop.getChildren()).toEqual([span('Caught an error: Hello')]);
});

it('provides component stack even if overriding prepareStackTrace', () => {
Error.prepareStackTrace = function(error, callsites) {
const stack = ['An error occurred:', error.message];
for (let i = 0; i < callsites.length; i++) {
const callsite = callsites[i];
stack.push(
'\t' + callsite.getFunctionName(),
'\t\tat ' + callsite.getFileName(),
'\t\ton line ' + callsite.getLineNumber(),
);
}

return stack.join('\n');
};

class ErrorBoundary extends React.Component {
state = {error: null, errorInfo: null};
componentDidCatch(error, errorInfo) {
this.setState({error, errorInfo});
}
render() {
if (this.state.errorInfo) {
Scheduler.unstable_yieldValue('render error message');
return (
<span
prop={`Caught an error:${normalizeCodeLocInfo(
this.state.errorInfo.componentStack,
)}.`}
/>
);
}
return this.props.children;
}
}

function BrokenRender(props) {
throw new Error('Hello');
}

ReactNoop.render(
<ErrorBoundary>
<BrokenRender />
</ErrorBoundary>,
);
expect(Scheduler).toFlushAndYield(['render error message']);
Error.prepareStackTrace = undefined;

expect(ReactNoop.getChildren()).toEqual([
span(
'Caught an error:\n' +
' in BrokenRender (at **)\n' +
' in ErrorBoundary (at **).',
),
]);
});

if (!ReactFeatureFlags.disableModulePatternComponents) {
it('handles error thrown inside getDerivedStateFromProps of a module-style context provider', () => {
function Provider() {
Expand Down
4 changes: 4 additions & 0 deletions packages/shared/ReactComponentStackFrame.js
Expand Up @@ -80,6 +80,9 @@ export function describeNativeComponentFrame(
let control;

reentry = true;
const previousPrepareStackTrace = Error.prepareStackTrace;
// $FlowFixMe It does accept undefined.
Error.prepareStackTrace = undefined;
let previousDispatcher;
if (__DEV__) {
previousDispatcher = ReactCurrentDispatcher.current;
Expand Down Expand Up @@ -184,6 +187,7 @@ export function describeNativeComponentFrame(
ReactCurrentDispatcher.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
}
// Fallback to just using the name if we couldn't make it throw.
const name = fn ? fn.displayName || fn.name : '';
Expand Down