尝试捕获Axios与React Query(suspension mode true)和NextJs一起使用的未捕获错误

bweufnob  于 2023-06-05  发布在  iOS
关注(0)|答案(1)|浏览(145)

我正在使用NextJS,React查询(带有axios和suspension模式),我试图从我的API中捕获错误,该API返回404 en目的。我成功地在error.js文件中捕获了它,但在控制台中出现了相同的错误“uncaught”

我试图在我的composant中记录和捕获这个错误,我也使用了react查询,但我仍然可以得到它并记录它,但它仍然在控制台中“未捕获”。
这里是我的家合成

我的路线

我的错误. js

你知道如何处理这个错误吗?

l0oc07j2

l0oc07j21#

我猜你的error.js没有捕捉和正确处理你的404错误。您的GlobalError组件只是记录useEffect()的错误。
我想您最好采用ErrorBoundary组件来成功地显示错误消息(在您的示例中,出现了错误!)

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
 
    // Define a state variable to track whether is an error or not
    this.state = { hasError: false };
  }
  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI
 
    return { hasError: true };
  }
  componentDidCatch(error, errorInfo) {
    // You can use your own error logging service here
    console.log({ error, errorInfo });
  }
  render() {
    // Check if the error is thrown
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return (
        <div>
          <h2>There was an error</h2>
          <button
            type="button"
            onClick={() => this.setState({ hasError: false })}
          >
            Try again?
          </button>
        </div>
      );
    }
 
    // Return children components in case of no error
 
    return this.props.children;
  }
}
 
export default ErrorBoundary;

相关问题