【问题标题】:How to trigger React error boundaries when Promises are rejected?当 Promises 被拒绝时如何触发 React 错误边界?
【发布时间】:2020-02-02 17:15:03
【问题描述】:

我遇到的问题是,promise 中抛出的错误没有被错误边界组件捕获。

代码从服务器获取数据并使用状态代码来确定如何处理来自响应的数据。 axios 用作客户端,并设置拦截器来处理响应。

API.interceptors.response.use((response) => {
  switch (response.status) {
    case 500:
    case 403:
      throw new Promise((resolve) => resolve(response.status));
  }
});

我已经设置了一个ErrorBoundary 组件来捕获其子组件中抛出的错误:

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

  componentDidCatch(error) {
    this.setState({
      hasError: true,
    });

    if (error instanceof Promise) {
      error.then(() => console.log(error));
    } else {
      console.log(error);
    }
  }

  render() {
    return this.state.hasError ? (
      <span>Something went wrong but it is okay</span>
    ) : (
      this.props.children
    );
  }
}

它被用作:

<ErrorBoundary>
  <Child />
</ErrorBoundary>

Child 组件在componentDidMount 方法中从服务器获取一些数据。

componentDidMount() {
  API.getData().then((data) => {
    ...
  });
}

当服务器响应一个导致Promise 被抛出的状态码时,ErrorBoundary 组件应该捕获它,但它没有。如果在 componentDidMount 方法中显式抛出错误,则错误边界会做出相应反应。例如:

componentDidMount() {
  throw new Error(); 
  // or throw new Promise(resolve => resolve());
}

catch 始终可以捕获错误,但有没有办法让ErrorBoundary 组件捕获这些错误?

【问题讨论】:

标签: javascript reactjs error-handling promise axios


【解决方案1】:

你可以试试react-error-boundary npm 包。他们有 useErrorHandler 钩子来处理异步代码。

请参阅此页面了解更多信息 - https://github.com/bvaughn/react-error-boundary#useerrorhandlererror-error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2017-08-18
    • 2012-10-28
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    相关资源
    最近更新 更多