Skip to content

Cross-origin error handling in DEV #10353

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 17 commits into from
Aug 3, 2017
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions fixtures/dom/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
-->
<title>React App</title>
<script src="https://unpkg.com/prop-types@15.5.6/prop-types.js"></script>
<script src="https://unpkg.com/expect@1.20.2/umd/expect.min.js"></script>
</head>
<body>
<div id="root"></div>
Expand Down
92 changes: 84 additions & 8 deletions fixtures/dom/src/components/fixtures/error-handling/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';

const React = window.React;
const ReactDOM = window.ReactDOM;

function BadRender(props) {
throw props.error;
props.doThrow();
}
class ErrorBoundary extends React.Component {
static defaultProps = {
buttonText: 'Trigger error',
};
state = {
shouldThrow: false,
didThrow: false,
Expand All @@ -23,15 +27,15 @@ class ErrorBoundary extends React.Component {
render() {
if (this.state.didThrow) {
if (this.state.error) {
return `Captured an error: ${this.state.error.message}`;
return <p>Captured an error: {this.state.error.message}</p>;
} else {
return `Captured an error: ${this.state.error}`;
return <p>Captured an error: {'' + this.state.error}</p>;
}
}
if (this.state.shouldThrow) {
return <BadRender error={this.props.error} />;
return <BadRender doThrow={this.props.doThrow} />;
}
return <button onClick={this.triggerError}>Trigger error</button>;
return <button onClick={this.triggerError}>{this.props.buttonText}</button>;
}
}
class Example extends React.Component {
Expand All @@ -42,13 +46,44 @@ class Example extends React.Component {
render() {
return (
<div>
<ErrorBoundary error={this.props.error} key={this.state.key} />
<button onClick={this.restart}>Reset</button>
<ErrorBoundary
buttonText={this.props.buttonText}
doThrow={this.props.doThrow}
key={this.state.key}
/>
</div>
);
}
}

class TriggerErrorAndCatch extends React.Component {
container = document.createElement('div');

triggerErrorAndCatch = () => {
try {
ReactDOM.flushSync(() => {
ReactDOM.render(
<BadRender
doThrow={() => {
throw new Error('Caught error');
}}
/>,
this.container
);
});
} catch (e) {}
};

render() {
return (
<button onClick={this.triggerErrorAndCatch}>
Trigger error and catch
</button>
);
}
}

export default class ErrorHandlingTestCases extends React.Component {
render() {
return (
Expand All @@ -69,7 +104,11 @@ export default class ErrorHandlingTestCases extends React.Component {
should be replaced with "Captured an error: Oops!" Clicking reset
should reset the test case.
</TestCase.ExpectedResult>
<Example error={new Error('Oops!')} />
<Example
doThrow={() => {
throw new Error('Oops!');
}}
/>
</TestCase>
<TestCase title="Throwing null" description="">
<TestCase.Steps>
Expand All @@ -80,7 +119,44 @@ export default class ErrorHandlingTestCases extends React.Component {
The "Trigger error" button should be replaced with "Captured an
error: null". Clicking reset should reset the test case.
</TestCase.ExpectedResult>
<Example error={null} />
<Example
doThrow={() => {
throw null; // eslint-disable-line no-throw-literal
}}
/>
</TestCase>
<TestCase
title="Cross-origin errors (development mode only)"
description="">
<TestCase.Steps>
<li>Click the "Trigger cross-origin error" button</li>
<li>Click the reset button</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The "Trigger error" button should be replaced with "Captured an
error: A cross-origin error was thrown [...]". The actual error message should
be logged to the console: "Uncaught Error: Expected true to
be false".
</TestCase.ExpectedResult>
<Example
buttonText="Trigger cross-origin error"
doThrow={() => {
// The `expect` module is loaded via unpkg, so that this assertion
// triggers a cross-origin error
window.expect(true).toBe(false);
}}
/>
</TestCase>
<TestCase
title="Errors are logged even if they're caught (development mode only)"
description="">
<TestCase.Steps>
<li>Click the "Trigger render error and catch" button</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
Open the console. "Uncaught Error: Caught error" should have been logged by the browser.
</TestCase.ExpectedResult>
<TriggerErrorAndCatch />
</TestCase>
</FixtureSet>
);
Expand Down
71 changes: 18 additions & 53 deletions src/renderers/shared/fiber/ReactFiberErrorLogger.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,28 +30,6 @@ function logCapturedError(capturedError: CapturedError): void {
}

const error = (capturedError.error: any);

// Duck-typing
let message;
let name;
let stack;

if (
error !== null &&
typeof error.message === 'string' &&
typeof error.name === 'string' &&
typeof error.stack === 'string'
) {
message = error.message;
name = error.name;
stack = error.stack;
} else {
// A non-error was thrown.
message = '' + error;
name = 'Error';
stack = '';
}

if (__DEV__) {
const {
componentName,
Expand All @@ -61,25 +39,9 @@ function logCapturedError(capturedError: CapturedError): void {
willRetry,
} = capturedError;

const errorSummary = message ? `${name}: ${message}` : name;

const componentNameMessage = componentName
? `React caught an error thrown by ${componentName}.`
: 'React caught an error thrown by one of your components.';

// Error stack varies by browser, eg:
// Chrome prepends the Error name and type.
// Firefox, Safari, and IE don't indent the stack lines.
// Format it in a consistent way for error logging.
let formattedCallStack = stack.slice(0, errorSummary.length) ===
errorSummary
? stack.slice(errorSummary.length)
: stack;
formattedCallStack = formattedCallStack
.trim()
.split('\n')
.map(line => `\n ${line.trim()}`)
.join();
? `The above error occurred in the <${componentName}> component:`
: 'The above error occurred in one of your React components:';

let errorBoundaryMessage;
// errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
Expand All @@ -90,25 +52,28 @@ function logCapturedError(capturedError: CapturedError): void {
`using the error boundary you provided, ${errorBoundaryName}.`;
} else {
errorBoundaryMessage =
`This error was initially handled by the error boundary ${errorBoundaryName}. ` +
`This error was initially handled by the error boundary ${errorBoundaryName}.\n` +
`Recreating the tree from scratch failed so React will unmount the tree.`;
}
} else {
errorBoundaryMessage =
'Consider adding an error boundary to your tree to customize error handling behavior. ' +
'See https://fb.me/react-error-boundaries for more information.';
'Consider adding an error boundary to your tree to customize error handling behavior.\n' +
'You can learn more about error boundaries at https://fb.me/react-error-boundaries.';
}

console.error(
`${componentNameMessage} You should fix this error in your code. ${errorBoundaryMessage}\n\n` +
`${errorSummary}\n\n` +
`The error is located at: ${componentStack}\n\n` +
`The error was thrown at: ${formattedCallStack}`,
);
const combinedMessage =
`${componentNameMessage}${componentStack}\n\n` +
`${errorBoundaryMessage}`;

// In development, we provide our own message with just the component stack.
// We don't include the original error message and JS stack because the browser
// has already printed it. Even if the application swallows the error, it is still
// displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
console.error(combinedMessage);
} else {
console.error(
`React caught an error thrown by one of your components.\n\n${error.stack}`,
);
// In production, we print the error directly.
// This will include the message, the JS stack, and anything the browser wants to show.
// We pass the error object instead of custom message so that the browser displays the error natively.
console.error(error);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should remove the message and name variables now. They don't seem to be used anymore.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

}
}

Expand Down
1 change: 1 addition & 0 deletions src/renderers/shared/fiber/ReactFiberScheduler.js
Original file line number Diff line number Diff line change
Expand Up @@ -1188,6 +1188,7 @@ module.exports = function<T, P, I, TI, PI, C, CX, PL>(
if (capturedErrors === null) {
capturedErrors = new Map();
}

capturedErrors.set(boundary, {
componentName,
componentStack,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -902,18 +902,15 @@ describe('ReactIncrementalErrorHandling', () => {

expect(console.error.calls.count()).toBe(1);
const errorMessage = console.error.calls.argsFor(0)[0];
expect(errorMessage).toContain(
'React caught an error thrown by ErrorThrowingComponent. ' +
'You should fix this error in your code. ' +
'Consider adding an error boundary to your tree to customize error handling behavior.',
);
expect(errorMessage).toContain('Error: componentWillMount error');
expect(normalizeCodeLocInfo(errorMessage)).toContain(
'The error is located at: \n' +
'The above error occurred in the <ErrorThrowingComponent> component:\n' +
' in ErrorThrowingComponent (at **)\n' +
' in span (at **)\n' +
' in div (at **)',
);
expect(errorMessage).toContain(
'Consider adding an error boundary to your tree to customize error handling behavior.',
);
});

it('should log errors that occur during the commit phase', () => {
Expand All @@ -936,18 +933,15 @@ describe('ReactIncrementalErrorHandling', () => {

expect(console.error.calls.count()).toBe(1);
const errorMessage = console.error.calls.argsFor(0)[0];
expect(errorMessage).toContain(
'React caught an error thrown by ErrorThrowingComponent. ' +
'You should fix this error in your code. ' +
'Consider adding an error boundary to your tree to customize error handling behavior.',
);
expect(errorMessage).toContain('Error: componentDidMount error');
expect(normalizeCodeLocInfo(errorMessage)).toContain(
'The error is located at: \n' +
'The above error occurred in the <ErrorThrowingComponent> component:\n' +
' in ErrorThrowingComponent (at **)\n' +
' in span (at **)\n' +
' in div (at **)',
);
expect(errorMessage).toContain(
'Consider adding an error boundary to your tree to customize error handling behavior.',
);
});

it('should ignore errors thrown in log method to prevent cycle', () => {
Expand Down Expand Up @@ -1026,15 +1020,17 @@ describe('ReactIncrementalErrorHandling', () => {
expect(handleErrorCalls.length).toBe(1);
expect(console.error.calls.count()).toBe(2);
expect(console.error.calls.argsFor(0)[0]).toContain(
'React caught an error thrown by ErrorThrowingComponent. ' +
'You should fix this error in your code. ' +
'React will try to recreate this component tree from scratch ' +
'The above error occurred in the <ErrorThrowingComponent> component:',
);
expect(console.error.calls.argsFor(0)[0]).toContain(
'React will try to recreate this component tree from scratch ' +
'using the error boundary you provided, ErrorBoundaryComponent.',
);
expect(console.error.calls.argsFor(1)[0]).toContain(
'React caught an error thrown by ErrorThrowingComponent. ' +
'You should fix this error in your code. ' +
'This error was initially handled by the error boundary ErrorBoundaryComponent. ' +
'The above error occurred in the <ErrorThrowingComponent> component:',
);
expect(console.error.calls.argsFor(1)[0]).toContain(
'This error was initially handled by the error boundary ErrorBoundaryComponent.\n' +
'Recreating the tree from scratch failed so React will unmount the tree.',
);
});
Expand Down
16 changes: 16 additions & 0 deletions src/renderers/shared/utils/ReactErrorUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,14 @@ if (__DEV__) {
let error;
// Use this to track whether the error event is ever called.
let didSetError = false;
let isCrossOriginError = false;

function onError(event) {
error = event.error;
didSetError = true;
if (error === null && event.colno === 0 && event.lineno === 0) {
isCrossOriginError = true;
}
}

// Create a fake event type.
Expand Down Expand Up @@ -240,6 +244,18 @@ if (__DEV__) {
'or switching to a modern browser. If you suspect that this is ' +
'actually an issue with React, please file an issue.',
);
} else if (isCrossOriginError) {
error = new Error(
"A cross-origin error was thrown. React doesn't have access to " +
'the actual error because it catches errors using a global ' +
'error handler, in order to preserve the "Pause on exceptions" ' +
'behavior of the DevTools. This is only an issue in DEV-mode; ' +
'in production, React uses a normal try-catch statement.\n\n' +
'If you are using React from a CDN, ensure that the <script> tag ' +
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be nice to say "If you are using React from a CDN in development, ensure ..." just to re-emphasize that this is only an issue in dev.

Copy link
Contributor

@bvaughn bvaughn Aug 5, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't it only a dev issue though? Since in production we use a regular try/catch instead of the funky global handler

Sorry. I read your statement twice as "to re-emphasize that this isn't only an issue in dev."

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR welcome :-)

'has a `crossorigin` attribute, and that it is served with the ' +
'`Access-Control-Allow-Origin: *` HTTP header. ' +
'See https://fb.me/react-cdn-crossorigin',
);
}
ReactErrorUtils._hasCaughtError = true;
ReactErrorUtils._caughtError = error;
Expand Down