【问题标题】:React js Error Boundary doesn't work with Promise CatchReact js 错误边界不适用于 Promise Catch
【发布时间】:2019-02-20 02:59:13
【问题描述】:

我们有一个错误边界组件:

import React from 'react';
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorMessage:''};
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true, errorMessage: error });
    // You can also log the error to an error reporting service
  }

  render() {
    if (this.state.hasError) {
      debugger
      // You can render any custom fallback UI  
      return <h1>{this.state.errorMessage.toString()}</h1>;
    }
    return this.props.children;
  }
}

export default ErrorBoundary;

我们是这样使用它的:

ReactDOM.render(
    <Provider store={store}>
        <Router>
            <CookiesProvider>
                <ErrorBoundary>
                    <NetworkMgmt />
                </ErrorBoundary>
            </CookiesProvider>
        </Router>
    </Provider>,
     document.getElementById('root')
);

之后我尝试使用下面的代码 sn-p 来抛出错误,但这不会调用错误边界 componentDidCatch(),而是抛出未处理的异常。

    dataService.getNetworkSummary().then(function (result) {
        debugger
        self.networks = result;
        self.setState({
            items: result.slice(0, 20),
            total: result.length,
            skip: 0,
            pageSize: 20,
            pageable: {
                buttonCount: 5,
                info: true,
                type: 'numeric',
                pageSizes: [20, 40, 60, 80, 100],
                previousNext: true
            },
            sortable:{
                allowUnsort: true,
                mode: 'single',
                sortDir:'Asc'
            }

        })
    }).catch(err =>
         {
             throw new Error("This is my error");
         });

有什么方法可以以正确的方式做到这一点。

【问题讨论】:

    标签: reactjs react-native error-handling react-redux react-router


    【解决方案1】:

    正如你正在捕捉错误的承诺一样,这意味着它不会在组件中显示错误,因为你已经在函数中处理了错误。 catch 的目的是处理该块中的错误而不干扰组件。如果你想手动抛出错误,你可以使用

    throw 'Some Error';
    

    或者您可以删除 catch 块,我不建议这样做。

    更新:错误边界在渲染期间、生命周期方法中以及它们下面的整个树的构造函数中捕获错误。

    【讨论】:

    • 我明白你的意思,但是在这种情况下,我有什么办法可以使用 ErrorBoundary 组件来处理我的异常/错误?
    • 错误边界在整个树的渲染、生命周期方法和构造函数中捕获错误。请尝试在渲染方法中抛出错误
    • 我是反应世界的新手,您有任何示例或链接来演示该行为。那真的很有帮助
    • @mayank,了解反应生命周期方法可能会有所帮助。 reactjs.org/docs/react-component.html
    • 链接真的很有用。但是正如@Umair 已经告诉过的,错误边界在渲染期间、生命周期方法中以及它们下面的整个树的构造函数中捕获错误。所以很明显,在我的情况下,ErrorBoundary 不会提供任何帮助。处理承诺异常的最佳方法是什么。有什么建议吗?
    猜你喜欢
    • 2020-01-16
    • 2020-06-25
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多