造一個 React 錯誤邊界的輪子

以下所有代碼都已整理到 Github:https://github.com/Haixiang6123/learn-error-bounday

參考的輪子:https://www.npmjs.com/package/react-error-boundary

發生甚麼事了

朋友們好啊,我是海怪,剛纔老闆對我說:海怪,發生甚麼事了,怎麼頁面白屏了?我說:怎麼回事?給我發了幾張截圖。我打開控制檯一看:

哦!原來是昨天,有個後端年輕人,說要和我聯調接口,我說:可以。然後,我說:小兄弟,你的數據儘量按我需要的格式來:

interface User {
    name: string;
    age: number;
}

interface GetUserListResponse {
    retcode: number;
    data: User[]
}

踏不服氣,他說你這個沒用,我說我這個有用,這是規範,傳統前後端聯調返回數據是要講規範的,對項目質量的提高可以起到四兩撥千斤的作用。100多萬行代碼的系統,只要有了類型規範,都不會輕易崩潰。他說試試,我說行。

我請求剛發出去,他的數據,啪!的一下就返回了!很快啊!!

{
    retcode: 0,
    data: [
        {name: '張三', age: 11},
        undefined,
        null
    ]
}

上來先是一個 retcode: 0,然後數組裏一個 User 對象,一個 undefined,一個 null,我全部用判斷 falsy 值防過去了啊:


if (!u) {
   return 0;
}

const trimName = u.name.trim();

return getScore(trimName);

防過去之後自然是正常處理業務邏輯和頁面展示。雖然沒有按照規範來,但是數組裏偶爾有個 falsy 值也還好,我把數組類型改成 Array<string | null | undefined>,沒有和他說,同事之間,點到爲止。我笑一下提交測試了,發了正式環境,準備收工。然後,這時候,老闆突然說線上白屏爆炸,我一看返回的數據:

{
    retcode: 0,
    data: [
        {name: '張三', age: 11},
        '找不到此用戶',
        '找不到此用戶',
        '找不到此用戶'
    ]
}

我大意了啊!沒有做類型判斷!馬上回滾。加了 if (typeof user === 'string') 的字符串類型判斷,準備再次發正式,但是我一想不對,難不成對每個數據我都要像像佛一樣供着?

// 這就很離譜
try {
    const scores = users.map(u => {
        // 判空
        if (!u) {
            return;
        }

        // 判斷錯誤類型
        if (typeof u === 'string') {
            return;
        }

        // 判斷屬性是否存在
        if (!u.name) {
            return;
        }

        const trimName = u.name.trim(0);

        return getScore(trimName);
    })

    return scores;
} catch (e) {
    return null;
}

這明顯是後端沒有對錯誤進行特殊處理啊,但是作爲前端開發就算被後端百般蹂躪,頁面也不應該白屏,應該就那個組件報錯就好了。我定了定神,決定使出“閃電五連鞭”

相信大家對JS異常捕獲很熟悉了,try-catch 一包業務代碼就收工了。不過,在組件裏對異常捕獲,需要用到的是 React 提供的 Error Boundary 錯誤邊界特性,用 componentDidCatch 鉤子來對頁面異常進行捕獲,以至於不會將異常擴散到整個頁面,有效防止頁面白屏。

下面,我來展示一下怎麼打好這套“閃電五連鞭”

第一鞭:抄

直接把官網例子抄下來,將 ErrorBoundary 組件輸出:

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

  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染能夠顯示降級後的 UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 你同樣可以將錯誤日誌上報給服務器
    logger.error(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 你可以自定義降級後的 UI 並渲染
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

然後將業務組件包裹:

<ErrorBoundary> // 捕獲錯誤
  <UserList /> // 使勁報錯
</ErrorBoundary>

如果 UserList 裏報錯,ErrorBoundary 就會捕獲,然後在 getDerivedStateFromError 裏更新組件狀態,render 裏就會顯示 Something went wrong,不會渲染 this.props.children

總結:
1. 將 ErrorBoundary 包裹可能出錯的業務組件
2. 當業務組件報錯時,會調用 componentDidCatch 鉤子裏的邏輯,將 hasError 設置 true,直接展示 <h1>

第二鞭:造個靈活的輪子

上面只是解決了燃眉之急,如果真要造一個好用的輪子,不應直接寫死 return <h1>Something went wrong</h1>,應該添加 props 來傳入報錯顯示內容(以下統稱爲 fallback):

// 出錯後顯示的元素類型
type FallbackElement = React.ReactElement<unknown, string | React.FC | typeof React.Component> | null;

// 出錯顯示組件的 props
export interface FallbackProps {
  error: Error;
}

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
  fallback?: FallbackElement;
  onError?: (error: Error, info: string) => void;
}

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryState {
  error: Error | null; // 將 hasError 的 boolean 改爲 Error 類型,提供更豐富的報錯信息
}

// 初始狀態
const initialState: ErrorBoundaryState = {
  error: null,
}

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  state = initialState;

  static getDerivedStateFromError(error: Error) {
    return {error};
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    if (this.props.onError) {
      this.props.onError(error, errorInfo.componentStack);
    }
  }

  render() {
    const {fallback} = this.props;
    const {error} = this.state;

    if (error !== null) {
      if (React.isValidElement(fallback)) {
        return fallback;
      }

      throw new Error('ErrorBoundary 組件需要傳入 fallback');
    }

    return this.props.children;
  }
}

export default ErrorBoundary

上面提供 onError 和 falback 兩個 props,前者爲出錯的回調,可以做錯誤信息上報或者用戶提示,後者則傳入錯誤提示內容,像下面這樣:

const App = () => {
  return (
    <ErrorBoundary fallback={<div>出錯啦</div>} onError={logger.error('出錯啦')}>
      <UserList />
    </ErrorBoundary>
  )
}

這已經讓 ErrorBoundary 變得稍微靈活一點了。但是有人就喜歡把 fallback 渲染函數、Fallback 組件作爲 props 傳入 ErrorBoundary,而不傳一段 ReactElement,所以爲了照顧更多人,將 fallback 進行擴展:

export declare function FallbackRender (props: FallbackProps): FallbackElement;

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
  fallback?: FallbackElement; // 一段 ReactElement
  FallbackComponent?: React.ComponentType<FallbackProps>; // Fallback 組件
  fallbackRender?: typeof FallbackRender; // 渲染 fallback 元素的函數
  onError?: (error: Error, info: string) => void;
}

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  ...

  render() {
    const {fallback, FallbackComponent, fallbackRender} = this.props;
    const {error} = this.state;
    
    // 多種 fallback 的判斷
    if (error !== null) {
      const fallbackProps: FallbackProps = {
        error,
      }
      // 判斷 fallback 是否爲合法的 Element
      if (React.isValidElement(fallback)) {
        return fallback;
      }
      // 判斷 render 是否爲函數
      if (typeof fallbackRender === 'function') {
        return (fallbackRender as typeof FallbackRender)(fallbackProps);
      }
      // 判斷是否存在 FallbackComponent
      if (FallbackComponent) {
        return <FallbackComponent {...fallbackProps} />
      }

      throw new Error('ErrorBoundary 組件需要傳入 fallback, fallbackRender, FallbackComponent 其中一個');
    }

    return this.props.children;
  }
}

上面提供 3 種方式來傳入出錯提示組件: fallback(元素)、FallbackComponent(組件),fallbackRender(render 函數)。現在使用輪子就更靈活了:

const App = () => {
  const onError = () => logger.error('出錯啦')
  
  return (
    <div>
      <ErrorBoundary fallback={<div>出錯啦</div>} onError={onError}>
        <UserList />
      </ErrorBoundary>
      
      <ErrorBoundary FallbackComponent={ErrorFallback} onError={onError}>
        <UserList />
      </ErrorBoundary>

      <ErrorBoundary
        fallbackRender={(fallbackProps) => <ErrorFallback {...fallbackProps} />}
        onError={onError}
      >
        <UserList />
      </ErrorBoundary> 
    </div>
  )
}

總結一下這裏的改動:
1. 將原來的 hasError 轉爲 error,從 boolean 轉爲 Error 類型,有利於獲得更多的錯誤信息,上報錯誤時很有用
2. 添加 fallback, FallbackComponent, fallbackRender 3個 props,提供多種方法來傳入展示 fallback

第三鞭:添加重置回調

有時候會遇到這種情況:服務器突然抽風了,503、502了,前端獲取不到響應,這時候某個組件報錯了,但是過一會又正常了。比較好的方法是允許用戶點一下 fallback 裏的一個按鈕來重新加載出錯組件,不需要重刷頁面,這樣的操作下面稱爲“重置”

同時,有些開發者也需要在重置裏添加自己邏輯,比如彈提示、日誌上報等。

圖解:

下面給出上面兩個需求的實現:

// 出錯後顯示的元素類型
type FallbackElement = React.ReactElement<unknown, string | React.FC | typeof React.Component> | null;

// 出錯顯示組件的 props
export interface FallbackProps {
  error: Error;
  resetErrorBoundary: () => void; // fallback 組件裏將該函數綁定到“重置”按鈕
}

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
  ...
  onReset?: () => void; // 開發者自定義重置邏輯,如日誌上報、 toast 提示
}

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  ...
  // 重置該組件狀態,將 error 設置 null
  reset = () => {
    this.setState(initialState);
  }

  // 執行自定義重置邏輯,並重置組件狀態  
  resetErrorBoundary = () => {
    if (this.props.onReset) {
      this.props.onReset();
    }
    this.reset();
  }

  render() {
    const {fallback, FallbackComponent, fallbackRender} = this.props;
    const {error} = this.state;

    if (error !== null) {
      const fallbackProps: FallbackProps = {
        error,
        resetErrorBoundary: this.resetErrorBoundary,  // 將 resetErrorBoundary 傳入 fallback
      }

      if (React.isValidElement(fallback)) {
        return fallback;
      }
      if (typeof fallbackRender === 'function') {
        return (fallbackRender as typeof FallbackRender)(fallbackProps);
      }
      if (FallbackComponent) {
        return <FallbackComponent {...fallbackProps} />
      }

      throw new Error('ErrorBoundary 組件需要傳入 fallback, fallbackRender, FallbackComponent 其中一個');
    }

    return this.props.children;
  }
}

改寫之後,在業務代碼中添加重置邏輯:

const App = () => {
  const onError = () => logger.error('出錯啦')
  const onReset = () => {
    console.log('已重置')
    message.info('剛剛出錯了,不好意思,現在已經重置好了,請找老闆錘這個開發')
  }
  // fallback 組件的渲染函數
  const renderFallback = (props: FallbackProps) => {
    return (
      <div>
        出錯啦,你可以<button onClick={props.resetErrorBoundary}>重置</button>
      </div>
    )
  }

  return (
    <div>
      <ErrorBoundary
        fallbackRender={renderFallback}
        onReset={onReset}
        onError={onError}
      >
        <UserList />
      </ErrorBoundary>
    </div>
  )
}

上面例子中,在 onReset 裏自定義想要重試的邏輯,然後在 renderFallback 裏將 props.resetErrorBoudnary 綁定到重置即可,當點擊“重置”時,就會調用 onReset ,同時將 ErrorBoundary 組件狀態清空(將 error 設爲 null)。

總結:
1. 添加 onReset 來實現重置的邏輯
2. 在 fallback 組件裏找個按鈕綁定 props.resetErrorBoundary 來觸發重置邏輯

第四鞭:監聽渲染以重置

上面的重置邏輯簡單也很實用,但是有時也會有侷限性:觸發重置的動作只能在 fallback 裏面。假如我的重置按鈕不在 fallback 裏呢?或者 onReset 函數根本不在這個 App 組件下那怎麼辦呢?難道要將 onReset 像傳家寶一路傳到這個 App 再傳入 ErrorBoundary 裏?

這時,我們就會想:能不能監聽狀態的更新,只要狀態更新就重置,反正就重新加載組件也沒什麼損失,這裏的狀態完全用全局狀態管理,放到 Redux 中。

上面的思路聽起來不就和 useEffect 裏的依賴項 deps 數組一樣嘛,不妨在 props 提供一個 resetKeys 數組,如果這個數組裏的東西變了,ErrorBoundary 就重置,這樣一控制是否要重置就更靈活了。馬上動手實現一下:

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
  ...
  resetKeys?: Array<unknown>;
}

// 檢查 resetKeys 是否有變化
const changedArray = (a: Array<unknown> = [], b: Array<unknown> = []) => {
  return a.length !== b.length || a.some((item, index) => !Object.is(item, b[index]));
}

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  ...

  componentDidUpdate(prevProps: Readonly<React.PropsWithChildren<ErrorBoundaryProps>>) {
    const {error} = this.state;
    const {resetKeys, onResetKeysChange} = this.props;
    
    // 只要 resetKeys 有變化,直接 reset
    if (changedArray(prevProps.resetKeys, resetKeys)) {
      // 重置 ErrorBoundary 狀態,並調用 onReset 回調
      this.reset();
    }
  }

  render() {
    ...
  }
}

首先,在 componentDidupdate 裏去做 resetKeys 的監聽,只要組件有 render 就看看 resetKeys 裏面的元素是否改過了,改過了就會重置。

但這裏又會有一個問題:萬一 resetKeys 裏元素是個 Date 或者一個對象怎麼辦?所以,我們還需要給開發者提供一種判斷 resetKeys 元素是否改變的方法,這裏就添加一個 onResetKeysChange 的 props 就好了:

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
  ...
  resetKeys?: Array<unknown>;
  onResetKeysChange?: (
    prevResetKey: Array<unknown> | undefined,
    resetKeys: Array<unknown> | undefined,
  ) => void;
}

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  ...

  componentDidUpdate(prevProps: Readonly<React.PropsWithChildren<ErrorBoundaryProps>>) {
    const {resetKeys, onResetKeysChange} = this.props;

    if (changedArray(prevProps.resetKeys, resetKeys)) {
      if (onResetKeysChange) {
        onResetKeysChange(prevProps.resetKeys, resetKeys);
      }

      // 重置 ErrorBoundary 狀態,並調用 onReset 回調
      this.reset();
    }
  }

  render() {
    ...
  }
}

changedArray 判定後,再次使用 props.onResetKeysChange 再次自定義判斷(如果有的話)resetKeys 裏的元素值是否有更新。

還有沒有問題呢?嗯,還有問題。這裏注意這裏的 componentDidUpdate 鉤子邏輯,假如某個 key 是觸發 error 的元兇,那麼就有可能觸發二次 error 的情況:

  1. xxxKey 觸發了 error,組件報錯
  2. 組件報錯導致 resetKeys 裏的一些東西改了
  3. componentDidUpdate 發現 resetKeys 裏有東西更新了,不廢話,馬上重置
  4. 重置完了,顯示報錯的組件,因爲 error 還存在(或者還未解決),報錯的組件又再次觸發了 error
  5. ...

所以要區分出來這一次到底是因爲 error 才 render 還是普通組件的 render,而且還需要確保當前有錯誤才重置,都沒錯誤還重置個毛。具體實現思路如圖所示:

實現如下

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  state = initialState;
  // 是否已經由於 error 而引發的 render/update
  updatedWithError = false;

  static getDerivedStateFromError(error: Error) {
    return {error};
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    if (this.props.onError) {
      this.props.onError(error, errorInfo.componentStack);
    }
  }
  
  componentDidUpdate(prevProps: Readonly<React.PropsWithChildren<ErrorBoundaryProps>>) {
    const {error} = this.state;
    const {resetKeys, onResetKeysChange} = this.props;
    
    // 已經存在錯誤,並且是第一次由於 error 而引發的 render/update,那麼設置 flag=true,不會重置 
    if (error !== null && !this.updatedWithError) {
      this.updatedWithError = true;
      return;
    }

    // 已經存在錯誤,並且是普通的組件 render,則檢查 resetKeys 是否有改動,改了就重置
    if (error !== null && changedArray(prevProps.resetKeys, resetKeys)) {
      if (onResetKeysChange) {
        onResetKeysChange(prevProps.resetKeys, resetKeys);
      }

      this.reset();
    }
  }

  reset = () => {
    this.updatedWithError = false;
    this.setState(initialState);
  }

  resetErrorBoundary = () => {
    if (this.props.onReset) {
      this.props.onReset();
    }
    this.reset();
  }

  render() {
    ...
  }
}

上面的改動有:

  1. updatedWithError 作爲 flag 判斷是否已經由於 error 出現而引發的 render/update
  2. 如果當前沒有錯誤,無論如何都不會重置
  3. 每次更新:當前存在錯誤,且第一次由於 error 出現而引發的 render/update,則設置 updatedWithError = true,不會重置狀態
  4. 每次更新:當前存在錯誤,且如果 updatedWithErrortrue 說明已經由於 error 而更新過了,以後的更新只要 resetKeys 裏的東西改了,都會被重置

至此,我們擁有了兩種可以實現重置的方式了:

方法 觸發範圍 使用場景 思想負擔
手動調用 resetErrorBoundary 一般在 fallback 組件裏 用戶可以在 fallback 裏手動點擊“重置”實現重置 最直接,思想負擔較輕
更新 resetKeys 哪裏都行,範圍更廣 用戶可以在報錯組件外部重置、resetKeys 裏有報錯組件依賴的數據、渲染時自動重置 間接觸發,要思考哪些值放到 resetKeys 裏,思想負擔較重

總結這一鞭的改動:
1. 添加 resetKeysonResetKeysChange 兩個 props,爲開發者提供監聽值變化而自動重置的功能
2. 在 componentDidUpdate 裏,只要不是由於 error 引發的組件渲染或更新,而且 resetKeys 有變化了,那麼直接重置組件狀態來達到自動重置

這裏自動重置還有一個好處:假如是由於網絡波動引發的異常,那頁面當然會顯示 fallback 了,如果用上面直接調用 props.resetErrorBoundary 方法來重置,只要用戶不點“重置”按鈕,那塊地方永遠不會被重置。又由於是因爲網絡波動引發的異常,有可能就那0.001 秒有問題,別的時間又好了,所以如果我們將一些變化頻繁的值放到 resetKeys 裏就很容易自動觸發重置。例如,報錯後,其它地方的值變了從而更改了 resetKeys 的元素值就會觸發自動重置。對於用戶來說,最多隻會看到一閃而過的 fallback,然後那塊地方又正常了。這樣一來,用戶也不需要親自觸發重置了。

第五鞭:輸出輪子

上面四鞭裏,到最後都是 export default ErrorBoundary 將組件輸出,如果代理裏很多個地方都要 catch error,就有這樣很囉嗦的代碼:

<div>
  <ErrorBoundary>
    <AAA/>
  </ErrorBoundary>
  <ErrorBoundary>
    <BBB/>
  </ErrorBoundary>
  <ErrorBoundary>
    <CCC/>
  </ErrorBoundary>
  <ErrorBoundary>
    <DDD/>
  </ErrorBoundary>
</div>

要處理這樣囉嗦的包裹,可以借鑑 React Router 的 withRouter 函數,我們也可以輸出一個高階函數 withErrorBoundary

/**
 * with 寫法
 * @param Component 業務組件
 * @param errorBoundaryProps error boundary 的 props
 */
function withErrorBoundary<P> (Component: React.ComponentType<P>, errorBoundaryProps: ErrorBoundaryProps): React.ComponentType<P> {
  const Wrapped: React.ComponentType<P> = props => {
    return (
      <ErrorBoundary {...errorBoundaryProps}>
        <Component {...props}/>
      </ErrorBoundary>
    )
  }

  // DevTools 顯示的組件名
  const name = Component.displayName ||Component.name || 'Unknown';
  Wrapped.displayName = `withErrorBoundary(${name})`;

  return Wrapped;
}

使用的時候就更簡潔了一些了:

// 業務子組件
const User = () => {
  return <div>User</div>
}

// 在業務組件加一層 ErrorBoundary
const UserWithErrorBoundary = withErrorBoundary(User, {
  onError: () => logger.error('出錯啦'),
  onReset: () => console.log('已重置')
})

// 業務父組件
const App = () => {
  return (
    <div>
      <UserWithErrorBoundary/>
    </div>
  )
}

其實 withXXX 這種寫法還可以寫成裝飾器,將 @withXXX 放到 class component 上也很方便,但是對於 functional component 就放不了了,有點受限,這裏不展開了。

還有沒有更好的設計呢?我們觀察到只有一些比較“嚴重的異常”瀏覽器纔會報錯,比如開頭提到的 TypeError: xxx is not a function。JS 是個動態類型語言,在瀏覽器裏你可以:NaN + 1,可以 NaN.toString(),可以 '1' + 1 都不報任何錯誤。其實官網也說了,對於一些錯誤 componenDidCatch 是不能自動捕獲的:

不過,這些錯誤在代碼裏開發者其實是知道的呀。既然開發者們有辦法拿到這些錯誤,那把錯誤直接拋出就可以讓 ErrorBoundary catch 到了:

  1. 有錯誤的時候,開發者自己調用 handleError(error) 將錯誤傳入函數中
  2. handleError 將錯誤 throw new Error(error)
  3. ErrorBoundary 發現有上面拋出的 Error,調用 componentDidCatch 處理錯誤
  4. ...

我來提供一種使用 React Hook 的實現方式:

/**
 * 自定義錯誤的 handler
 * @param givenError
 */
function useErrorHandler<P=Error>(
  givenError?: P | null | undefined,
): React.Dispatch<React.SetStateAction<P | null>> {
  const [error, setError] = React.useState<P | null>(null);
  if (givenError) throw givenError; // 初始有錯誤時,直接拋出
  if (error) throw error; // 後來再有錯誤,也直接拋出
  return setError; // 返回開發者可手動設置錯誤的鉤子
}

使用上面的 hook,對於一些需要自己處理的錯誤,可以有兩種處理方法:

  1. const handleError = useErrorHandler(),然後 handleError(yourError)
  2. useErrorHandler(otherHookError),如果別的 hooks 裏有 export error,完全可以直接將這個 error 傳入 useErrorHandler,直接處理

比如:

function Greeting() {
  const [greeting, setGreeting] = React.useState(null)
  const handleError = useErrorHandler()

  function handleSubmit(event) {
    event.preventDefault()
    const name = event.target.elements.name.value
    fetchGreeting(name).then(
      newGreeting => setGreeting(newGreeting),
      handleError, // 開發者自己處理錯誤,將錯誤拋出
    )
  }

  return greeting ? (
    <div>{greeting}</div>
  ) : (
    <form onSubmit={handleSubmit}>
      <label>Name</label>
      <input id="name" />
      <button type="submit">get a greeting</button>
    </form>
  )
}
// 用 ErrorBoundary 包裹,處理手動拋出的錯誤
export default withErrorBoundary(Greeting)

或者:

function Greeting() {
  const [name, setName] = React.useState('')
  const {greeting, error} = useGreeting(name)

  // 開發者自己處理錯誤,將錯誤拋出
  useErrorHandler(error)

  function handleSubmit(event) {
    event.preventDefault()
    const name = event.target.elements.name.value
    setName(name)
  }

  return greeting ? (
    <div>{greeting}</div>
  ) : (
    <form onSubmit={handleSubmit}>
      <label>Name</label>
      <input id="name" />
      <button type="submit">get a greeting</button>
    </form>
  )
}

// 用 ErrorBoundary 包裹,處理手動拋出的錯誤
export default withErrorBoundary(Greeting)

總結:
1. 提供 withErrorBoundary 方法來包裹業務組件實現異常捕獲
2. 提供 useErrorHandler hook 讓開發者自己處理/拋出錯誤

“閃電五連鞭”總結

再次總結一下“抓錯五連鞭”的要點:

  1. 造一個 ErrorBoundary 輪子
  2. componentDidCatch 捕獲頁面報錯,getDerivedStateFromError 更新 ErrorBoundary 的 state,並獲取具體 error
  3. 提供多種展示錯誤內容入口:fallback, FallbackComponent, fallbackRender
  4. 重置鉤子:提供 onReset, resetErrorBoundary 的傳值和調用,以實現重置
  5. 重置監聽數組:監聽 resetKeys 的變化來重置。對於擁有複雜元素的 resetKeys 數組提供 onResetKeysChange 讓開發者自行判斷。在 componentDidUpdate 裏監聽每次渲染時 resetKeys 變化,並設置 updatedWithError 作爲 flag 判斷是否由於 error 引發的渲染,對於普通渲染,只要 resetKeys 變化,直接重置
  6. 提供 ErrorBoundary 的2種使用方法:嵌套業務組件,將業務組件傳入withErrorBoundary 高階函數。提供 useErrorBoundary 鉤子給開發者自己拋出 ErrorBoundary 不能自動捕獲的錯誤

耗子尾汁,好好反思

打完了這一套“五連鞭”,再次發佈上線,一切OK。

然後我找到這位後端,跟他說了線上事故。當時他就流眼淚了,捂着臉,兩分多鐘以後,就好了。

我說:小夥子,你不講碼德你不懂。他說:對不起,我不懂規矩。後來他說他寫了好幾年動態語言,啊,看來是有 bear 來。這個年輕人不講碼德。來!騙!來!偷襲我一個24歲小前端,這好嗎?這不好,我勸,這位後端,耗子尾汁,好好反思,以後不要搞這樣的聰明,小聰明。程序猿要以和爲貴,要講碼德,不要搞窩裏鬥。

謝謝朋友們。

(故事純屬虛構,如有雷同,請自我檢討或者一鍵三連)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章