我有以下代码index.tsx
:
window.onerror = function(msg, url, line, col, error) {
debugger;
// Note that col & error are new to the HTML 5 spec and may not be
// supported in every browser. It worked for me in Chrome.
var extra = !col ? '' : '\ncolumn: ' + col;
extra += !error ? '' : '\nerror: ' + error;
// You can view the information in an alert to see things working like this:
alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);
// TODO: Report this error via ajax so you can keep track
// of what pages have JS issues
var suppressErrorAlert = true;
// If you return true, then error alerts (like in older versions of
// Internet Explorer) will be suppressed.
return suppressErrorAlert;
};
来源:
https://stackoverflow.com/a/10556743/3850405
如果我在另一个组件中抛出这样的错误,我会按预期捕获它:
componentDidMount() {
throw new Error();
}
如果像这样抛出:
async componentDidMount() {
throw new Error();
}
错误未被捕获并Unhandled Rejection (Error):
显示。
然后我尝试创建一个 React 全局错误边界。
import React, { ErrorInfo } from 'react';
interface IProps {
}
interface IState {
hasError: boolean
}
class ErrorBoundary extends React.PureComponent<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error: Error, info: ErrorInfo) {
// Display fallback UI
debugger;
console.warn(error);
console.warn(info);
this.setState({ hasError: true });
// You can also log the error to an error reporting service
//logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary
索引.tsx:
<React.StrictMode>
<Provider store={store}>
<ConnectedIntlProvider>
<Router>
<ErrorBoundary>
<App />
</ErrorBoundary>
</Router>
</ConnectedIntlProvider>
</Provider>
</React.StrictMode>,
资料来源:
https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html
https://stackoverflow.com/a/51764435/3850405
然而,效果是一样的,async componentDidMount
没有被发现,但它按预期工作。
我发现这个线程提到了这个问题,但没有真正的解决方案。
https://stackoverflow.com/a/56800470/3850405
如何在 React 中创建一个真正捕获所有内容的全局错误处理程序?