全局捕获反应错误

时间:2016-10-25 08:20:12

标签: javascript reactjs error-handling exception-handling react-redux

我是React的新手。我想捕获所有反应未捕获和意外错误/警告,我想将错误记录到外部API。我知道它可能通过Try Catch方法,但我计划将其全局化,以便其他开发人员不必每次都编写代码。

我尝试了window.onerror/addEventListener('error', function(e){},它只捕获了Javascript错误但没有反应错误。

这类似于帖子How do I handle exceptions?。但是给出的解决方案并不能满足我的需求。

有人可以帮我吗?

3 个答案:

答案 0 :(得分:0)

这将有助于:https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

基本上,对于React 16及更高版本,您可以在父级大多数组件中使用componentDidCatch()生命周期方法来记录所有未捕获的异常。

答案 1 :(得分:0)

文档参考:https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

实施示例的实际情况:

// app.js
const MOUNT_NODE = document.getElementById('app');

const render = (messages) => {
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={messages}>
        <ConnectedRouter history={history}>
          <ErrorBoundary>
            <App />
          </ErrorBoundary>
        </ConnectedRouter>
      </LanguageProvider>
    </Provider>,
    MOUNT_NODE
  );
};

// ErrorBoundary component
export default class ErrorBoundary {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
  }

  render() {
    if (this.state.hasError) {
      return (
        <div>
          // error message
        </div>
      );
    }

    return this.props.children;
  }
}

答案 2 :(得分:0)

需要注意的是,async之类的async componentDidMount方法中的错误不会被error boundary捕获。

https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event

由于不会捕获所有错误,因此我们决定在项目中使用普通JavaScript window.onerrorwindow.onunhandledrejection

完整的问题和答案:

https://stackoverflow.com/a/64319415/3850405