[React] Using React Error Boundaries to handle errors in React Components

No matter how hard you try, eventually your app code just isn’t going to behave the way you expect it to and you’ll need to handle those exceptions. If a render is thrown and unhandled, your application will be removed from the page, leaving the user with a blank screen... Kind of awkward...

Luckily for us, there’s a simple way to handle errors in your application using a special kind of component called an Error Boundary. Unfortunately, there is currently no way to create an Error Boundary component with a function and you have to use a class component instead, but we got another lucky break because there’s a terrific open source library we can use called react-error-boundary.

In this lesson, we’ll learn how to write our own simple error boundary and then how to use react-error-boundary instead. We’ll also learn the implications of where we place our Error Boundaries in our React component tree.

 

复制代码
<body>
  <div id="root"></div>
  <script src="https://unpkg.com/react@16.12.0/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script>
  <script src="https://unpkg.com/react-error-boundary@1.2.5/dist/umd/react-error-boundary.js"></script>
  <script type="text/babel">
    const ErrorBoundary = ReactErrorBoundary.ErrorBoundary

    function ErrorFallback({error}) {
      return (
        <div>
          <p>Something went wrong:</p>
          <pre>{error.message}</pre>
        </div>
      )
    }

    function Bomb() {
      throw new Error('💥 CABOOM 💥')
    }

    function App() {
      const [explode, setExplode] = React.useState(false)
      return (
        <div>
          <div>
            <button onClick={() => setExplode(true)}>💣</button>
          </div>
          <div>
            <ErrorBoundary FallbackComponent={ErrorFallback}>
              {explode ? <Bomb /> : 'Push the button Max!'}
            </ErrorBoundary>
          </div>
        </div>
      )
    }
    ReactDOM.render(<App />, document.getElementById('root'))
  </script>
</body>
复制代码

 

posted @   Zhentiw  阅读(178)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-03-31 [PureScript] Break up Expressions into Cases in PureScript using Simple Pattern Matching
2019-03-31 [Docker] Hooking a Volume to Node.js Source Code
2016-03-31 [React] React Router: setRouteWillLeaveHook
点击右上角即可分享
微信分享提示