mirror of
https://github.com/zebrajr/react.git
synced 2025-12-06 00:20:04 +01:00
Cross-origin error handling in DEV (#10353)
* Add DOM fixture for cross-origin errors
* Use a custom error object in place of cross-origin errors
Cross-origin errors aren't accessible by React in DEV mode because we
catch errors using a global error handler, in order to preserve the
"Pause on exceptions" behavior of the DevTools. When this happens, we
should use a custom error object that explains what happened.
For uncaught errors, the actual error message is logged to the console
by the browser, so React should skip logging the message again.
* Add test case that demonstrates errors are logged even if they're caught
* Don't double log error messages in DEV
In DEV, the browser always logs errors thrown inside React components,
even if the originating update is wrapped in a try-catch, because of the
dispatchEvent trick used by invokeGuardedCallback. So the error logger
should not log the message again.
* Fix tests
* Change how error is printed in DEV and PROD
In DEV, we don't want to print the stack trace because the browser already always prints it.
We'll just print the component stack now.
In PROD, we used to omit the JS error message. However we *do* want to show it because
if the application swallows the error, the browser will *not* print it. In DEV it works
only because of the fake event trick. So in PROD we will always print the underlying error
by logging the error object directly. This will show both the message and the JS stack.
* Make the wording tighter and emphasize the real error is above
There's a few goals in the rewording:
* Make it tighter using line breaks between sentences.
* Make it slightly less patronizing ("You should fix it" => "You can find its details in an earlier log")
* ^^ This also helps highlight that the real error message and stack is above
* Group subsections: intro (there's an error), component stack, and final addendum about error boundaries
* ^^ Otherwise people might think error boundaries are part of the reason they have an error
* Make it clear "located at" is not the stacktrace. Otherwise it feels confusing. This makes it clearer you should still look for stack trace (with other details) above and introduces the concept of component stack.
* Make the message shorter
* Unused variables
* Fix an error caused by fixing lint
* One more bikeshed
* Fix fixture
* Remove unused file
* Concise wording
* Unused variables
This commit is contained in:
parent
028e0ea937
commit
a650699d2f
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
@ -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 {
|
||||
|
|
@ -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 (
|
||||
|
|
@ -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>
|
||||
|
|
@ -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>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
@ -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.
|
||||
|
|
@ -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.';
|
||||
}
|
||||
const combinedMessage =
|
||||
`${componentNameMessage}${componentStack}\n\n` +
|
||||
`${errorBoundaryMessage}`;
|
||||
|
||||
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}`,
|
||||
);
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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', () => {
|
||||
|
|
@ -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', () => {
|
||||
|
|
@ -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.',
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
@ -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 ' +
|
||||
'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;
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user