[React] Handle React Suspense Errors with an Error Boundary

Error Boundaries are the way you handle errors with React, and Suspense embraces this completely. Let's take a look at how to handle asynchronous errors with Suspense and Error Boundaries.

 

In previous post, we used React.Suspense with fallback (for loading..), in this post, we will see how to handle error case with ErrorBoundary. https://reactjs.org/docs/error-boundaries.html

NPM module: https://npm.im/react-error-boundary

 

One important thing to note is that our error boundary can only handle certain errors, specifically errors that are happening within the React call stack.

It won't handle errors that are happening in event handlers or if there's an error in an asynchronous callback, like a promise handler. It will only handle errors that happen within a React call stack, like the render method or a React useEffect callback.

 

An ErrorBoundary component:

复制代码
// utils.js

class ErrorBoundary extends React.Component {
  state = {error: null}
  static getDerivedStateFromError(error) {
    return {error}
  }
  componentDidCatch() {
    // log the error to the server
  }
  tryAgain = () => this.setState({error: null})
  render() {
    return this.state.error ? (
      <div>
        There was an error. <button onClick={this.tryAgain}>try again</button>
        <pre style={{whiteSpace: 'normal'}}>{this.state.error.message}</pre>
      </div>
    ) : (
      this.props.children
    )
  }
}
复制代码

 

---

 

复制代码
import React from 'react'
import fetchPokemon from '../fetch-pokemon'
import {PokemonDataView, ErrorBoundary} from '../utils'

let pokemon
let pokemonError
let pokemonPromise = fetchPokemon('pikachue').then(
  p => {
    console.log('promise resolve')
    pokemon = p
  },
  e => {
    pokemonError = e
  },
)

function PokemonInfo() {
  console.log('PokemonInfo init')

  if (pokemonError) {
    throw pokemonError
  }

  if (!pokemon) {
    throw pokemonPromise // this API might change
  }

  return (
    <div>
      <div className="pokemon-info__img-wrapper">
        <img src={pokemon.image} alt={pokemon.name} />
      </div>
      <PokemonDataView pokemon={pokemon} />
    </div>
  )
}

function App() {
  return (
    <div className="pokemon-info">
      <ErrorBoundary>
        <React.Suspense
          fallback={
            console.log('loading pokemon...') && <div>Loading pokemon...</div>
          }
        >
          <PokemonInfo />
        </React.Suspense>
      </ErrorBoundary>
    </div>
  )
}

export default App
复制代码

 

posted @   Zhentiw  阅读(811)  评论(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-09-02 [Functional Programming] Rewrite a reducer with functional state ADT
2019-09-02 [Angular] Using Pipe for function memoization
2018-09-02 [Spring] Properties for project configuration
2018-09-02 [Spring] Bean Scope Singleton cs Prototype
2017-09-02 [React] Remove React PropTypes by using Flow Annotations (in CRA)
2016-09-02 [Ramda] Compose and Curry
2015-09-02 [React] React Fundamentals: with-addons - ReactLink
点击右上角即可分享
微信分享提示