以下所有代碼都已整理到 Github:https://github.com/Haixiang6123/learn-error-bounday
發(fā)生甚么事了

朋友們好啊,我是海怪,剛才老板對(duì)我說(shuō):海怪,發(fā)生甚么事了,怎么頁(yè)面白屏了?我說(shuō):怎么回事?給我發(fā)了幾張截圖。我打開(kāi)控制臺(tái)一看:

哦!原來(lái)是昨天,有個(gè)后端年輕人,說(shuō)要和我聯(lián)調(diào)接口,我說(shuō):可以。然后,我說(shuō):小兄弟,你的數(shù)據(jù)盡量按我需要的格式來(lái):
interface User {
name: string;
age: number;
}
interface GetUserListResponse {
retcode: number;
data: User[]
}
踏不服氣,他說(shuō)你這個(gè)沒(méi)用,我說(shuō)我這個(gè)有用,這是規(guī)范,傳統(tǒng)前后端聯(lián)調(diào)返回?cái)?shù)據(jù)是要講規(guī)范的,對(duì)項(xiàng)目質(zhì)量的提高可以起到四兩撥千斤的作用。100多萬(wàn)行代碼的系統(tǒng),只要有了類(lèi)型規(guī)范,都不會(huì)輕易崩潰。他說(shuō)試試,我說(shuō)行。
我請(qǐng)求剛發(fā)出去,他的數(shù)據(jù),啪!的一下就返回了!很快?。。?/p>
{
retcode: 0,
data: [
{name: '張三', age: 11},
undefined,
null
]
}
上來(lái)先是一個(gè) retcode: 0,然后數(shù)組里一個(gè) User 對(duì)象,一個(gè) undefined,一個(gè) null,我全部用判斷 falsy 值防過(guò)去了?。?/p>
if (!u) {
return 0;
}
const trimName = u.name.trim();
return getScore(trimName);
防過(guò)去之后自然是正常處理業(yè)務(wù)邏輯和頁(yè)面展示。雖然沒(méi)有按照規(guī)范來(lái),但是數(shù)組里偶爾有個(gè) falsy 值也還好,我把數(shù)組類(lèi)型改成 Array<string | null | undefined>,沒(méi)有和他說(shuō),同事之間,點(diǎn)到為止。我笑一下提交測(cè)試了,發(fā)了正式環(huán)境,準(zhǔn)備收工。然后,這時(shí)候,老板突然說(shuō)線上白屏爆炸,我一看返回的數(shù)據(jù):
{
retcode: 0,
data: [
{name: '張三', age: 11},
'找不到此用戶',
'找不到此用戶',
'找不到此用戶'
]
}
我大意了?。](méi)有做類(lèi)型判斷!馬上回滾。加了 if (typeof user === 'string') 的字符串類(lèi)型判斷,準(zhǔn)備再次發(fā)正式,但是我一想不對(duì),難不成對(duì)每個(gè)數(shù)據(jù)我都要像像佛一樣供著?
// 這就很離譜
try {
const scores = users.map(u => {
// 判空
if (!u) {
return;
}
// 判斷錯(cuò)誤類(lèi)型
if (typeof u === 'string') {
return;
}
// 判斷屬性是否存在
if (!u.name) {
return;
}
const trimName = u.name.trim(0);
return getScore(trimName);
})
return scores;
} catch (e) {
return null;
}
這明顯是后端沒(méi)有對(duì)錯(cuò)誤進(jìn)行特殊處理啊,但是作為前端開(kāi)發(fā)就算被后端百般蹂躪,頁(yè)面也不應(yīng)該白屏,應(yīng)該就那個(gè)組件報(bào)錯(cuò)就好了。我定了定神,決定使出“閃電五連鞭”。

相信大家對(duì)JS異常捕獲很熟悉了,try-catch 一包業(yè)務(wù)代碼就收工了。不過(guò),在組件里對(duì)異常捕獲,需要用到的是 React 提供的 Error Boundary 錯(cuò)誤邊界特性,用 componentDidCatch 鉤子來(lái)對(duì)頁(yè)面異常進(jìn)行捕獲,以至于不會(huì)將異常擴(kuò)散到整個(gè)頁(yè)面,有效防止頁(yè)面白屏。
下面,我來(lái)展示一下怎么打好這套“閃電五連鞭”。
第一鞭:抄
直接把官網(wǎng)例子抄下來(lái),將 ErrorBoundary 組件輸出:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// 更新 state 使下一次渲染能夠顯示降級(jí)后的 UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// 你同樣可以將錯(cuò)誤日志上報(bào)給服務(wù)器
logger.error(error, errorInfo);
}
render() {
if (this.state.hasError) {
// 你可以自定義降級(jí)后的 UI 并渲染
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
然后將業(yè)務(wù)組件包裹:
<ErrorBoundary> // 捕獲錯(cuò)誤
<UserList /> // 使勁報(bào)錯(cuò)
</ErrorBoundary>
如果 UserList 里報(bào)錯(cuò),ErrorBoundary 就會(huì)捕獲,然后在 getDerivedStateFromError 里更新組件狀態(tài),render 里就會(huì)顯示 Something went wrong,不會(huì)渲染 this.props.children。

總結(jié):
1. 將 ErrorBoundary 包裹可能出錯(cuò)的業(yè)務(wù)組件
2. 當(dāng)業(yè)務(wù)組件報(bào)錯(cuò)時(shí),會(huì)調(diào)用 componentDidCatch 鉤子里的邏輯,將 hasError 設(shè)置 true,直接展示 <h1>
第二鞭:造個(gè)靈活的輪子
上面只是解決了燃眉之急,如果真要造一個(gè)好用的輪子,不應(yīng)直接寫(xiě)死 return <h1>Something went wrong</h1>,應(yīng)該添加 props 來(lái)傳入報(bào)錯(cuò)顯示內(nèi)容(以下統(tǒng)稱(chēng)為 fallback):
// 出錯(cuò)后顯示的元素類(lèi)型
type FallbackElement = React.ReactElement<unknown, string | React.FC | typeof React.Component> | null;
// 出錯(cuò)顯示組件的 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 類(lèi)型,提供更豐富的報(bào)錯(cuò)信息
}
// 初始狀態(tài)
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 兩個(gè) props,前者為出錯(cuò)的回調(diào),可以做錯(cuò)誤信息上報(bào)或者用戶提示,后者則傳入錯(cuò)誤提示內(nèi)容,像下面這樣:
const App = () => {
return (
<ErrorBoundary fallback={<div>出錯(cuò)啦</div>} onError={logger.error('出錯(cuò)啦')}>
<UserList />
</ErrorBoundary>
)
}
這已經(jīng)讓 ErrorBoundary 變得稍微靈活一點(diǎn)了。但是有人就喜歡把 fallback 渲染函數(shù)、Fallback 組件作為 props 傳入 ErrorBoundary,而不傳一段 ReactElement,所以為了照顧更多人,將 fallback 進(jìn)行擴(kuò)展:
export declare function FallbackRender (props: FallbackProps): FallbackElement;
// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
fallback?: FallbackElement; // 一段 ReactElement
FallbackComponent?: React.ComponentType<FallbackProps>; // Fallback 組件
fallbackRender?: typeof FallbackRender; // 渲染 fallback 元素的函數(shù)
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 是否為函數(shù)
if (typeof fallbackRender === 'function') {
return (fallbackRender as typeof FallbackRender)(fallbackProps);
}
// 判斷是否存在 FallbackComponent
if (FallbackComponent) {
return <FallbackComponent {...fallbackProps} />
}
throw new Error('ErrorBoundary 組件需要傳入 fallback, fallbackRender, FallbackComponent 其中一個(gè)');
}
return this.props.children;
}
}
上面提供 3 種方式來(lái)傳入出錯(cuò)提示組件: fallback(元素)、FallbackComponent(組件),fallbackRender(render 函數(shù))?,F(xiàn)在使用輪子就更靈活了:
const App = () => {
const onError = () => logger.error('出錯(cuò)啦')
return (
<div>
<ErrorBoundary fallback={<div>出錯(cuò)啦</div>} onError={onError}>
<UserList />
</ErrorBoundary>
<ErrorBoundary FallbackComponent={ErrorFallback} onError={onError}>
<UserList />
</ErrorBoundary>
<ErrorBoundary
fallbackRender={(fallbackProps) => <ErrorFallback {...fallbackProps} />}
onError={onError}
>
<UserList />
</ErrorBoundary>
</div>
)
}
總結(jié)一下這里的改動(dòng):
1. 將原來(lái)的 hasError 轉(zhuǎn)為 error,從 boolean 轉(zhuǎn)為 Error 類(lèi)型,有利于獲得更多的錯(cuò)誤信息,上報(bào)錯(cuò)誤時(shí)很有用
2. 添加 fallback, FallbackComponent, fallbackRender 3個(gè) props,提供多種方法來(lái)傳入展示 fallback
第三鞭:添加重置回調(diào)
有時(shí)候會(huì)遇到這種情況:服務(wù)器突然抽風(fēng)了,503、502了,前端獲取不到響應(yīng),這時(shí)候某個(gè)組件報(bào)錯(cuò)了,但是過(guò)一會(huì)又正常了。比較好的方法是允許用戶點(diǎn)一下 fallback 里的一個(gè)按鈕來(lái)重新加載出錯(cuò)組件,不需要重刷頁(yè)面,這樣的操作下面稱(chēng)為“重置”。
同時(shí),有些開(kāi)發(fā)者也需要在重置里添加自己邏輯,比如彈提示、日志上報(bào)等。
圖解:

下面給出上面兩個(gè)需求的實(shí)現(xiàn):
// 出錯(cuò)后顯示的元素類(lèi)型
type FallbackElement = React.ReactElement<unknown, string | React.FC | typeof React.Component> | null;
// 出錯(cuò)顯示組件的 props
export interface FallbackProps {
error: Error;
resetErrorBoundary: () => void; // fallback 組件里將該函數(shù)綁定到“重置”按鈕
}
// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
...
onReset?: () => void; // 開(kāi)發(fā)者自定義重置邏輯,如日志上報(bào)、 toast 提示
}
class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
...
// 重置該組件狀態(tài),將 error 設(shè)置 null
reset = () => {
this.setState(initialState);
}
// 執(zhí)行自定義重置邏輯,并重置組件狀態(tài)
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 其中一個(gè)');
}
return this.props.children;
}
}
改寫(xiě)之后,在業(yè)務(wù)代碼中添加重置邏輯:
const App = () => {
const onError = () => logger.error('出錯(cuò)啦')
const onReset = () => {
console.log('已重置')
message.info('剛剛出錯(cuò)了,不好意思,現(xiàn)在已經(jīng)重置好了,請(qǐng)找老板錘這個(gè)開(kāi)發(fā)')
}
// fallback 組件的渲染函數(shù)
const renderFallback = (props: FallbackProps) => {
return (
<div>
出錯(cuò)啦,你可以<button onClick={props.resetErrorBoundary}>重置</button>
</div>
)
}
return (
<div>
<ErrorBoundary
fallbackRender={renderFallback}
onReset={onReset}
onError={onError}
>
<UserList />
</ErrorBoundary>
</div>
)
}
上面例子中,在 onReset 里自定義想要重試的邏輯,然后在 renderFallback 里將 props.resetErrorBoudnary 綁定到重置即可,當(dāng)點(diǎn)擊“重置”時(shí),就會(huì)調(diào)用 onReset ,同時(shí)將 ErrorBoundary 組件狀態(tài)清空(將 error 設(shè)為 null)。
總結(jié):
1. 添加 onReset 來(lái)實(shí)現(xiàn)重置的邏輯
2. 在 fallback 組件里找個(gè)按鈕綁定 props.resetErrorBoundary 來(lái)觸發(fā)重置邏輯
第四鞭:監(jiān)聽(tīng)渲染以重置
上面的重置邏輯簡(jiǎn)單也很實(shí)用,但是有時(shí)也會(huì)有局限性:觸發(fā)重置的動(dòng)作只能在 fallback 里面。假如我的重置按鈕不在 fallback 里呢?或者 onReset 函數(shù)根本不在這個(gè) App 組件下那怎么辦呢?難道要將 onReset 像傳家寶一路傳到這個(gè) App 再傳入 ErrorBoundary 里?
這時(shí),我們就會(huì)想:能不能監(jiān)聽(tīng)狀態(tài)的更新,只要狀態(tài)更新就重置,反正就重新加載組件也沒(méi)什么損失,這里的狀態(tài)完全用全局狀態(tài)管理,放到 Redux 中。
上面的思路聽(tīng)起來(lái)不就和 useEffect 里的依賴(lài)項(xiàng) deps 數(shù)組一樣嘛,不妨在 props 提供一個(gè) resetKeys 數(shù)組,如果這個(gè)數(shù)組里的東西變了,ErrorBoundary 就重置,這樣一控制是否要重置就更靈活了。馬上動(dòng)手實(shí)現(xiàn)一下:
// 本組件 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 狀態(tài),并調(diào)用 onReset 回調(diào)
this.reset();
}
}
render() {
...
}
}
首先,在 componentDidupdate 里去做 resetKeys 的監(jiān)聽(tīng),只要組件有 render 就看看 resetKeys 里面的元素是否改過(guò)了,改過(guò)了就會(huì)重置。
但這里又會(huì)有一個(gè)問(wèn)題:萬(wàn)一 resetKeys 里元素是個(gè) Date 或者一個(gè)對(duì)象怎么辦?所以,我們還需要給開(kāi)發(fā)者提供一種判斷 resetKeys 元素是否改變的方法,這里就添加一個(gè) 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 狀態(tài),并調(diào)用 onReset 回調(diào)
this.reset();
}
}
render() {
...
}
}
在 changedArray 判定后,再次使用 props.onResetKeysChange 再次自定義判斷(如果有的話)resetKeys 里的元素值是否有更新。
還有沒(méi)有問(wèn)題呢?嗯,還有問(wèn)題。這里注意這里的 componentDidUpdate 鉤子邏輯,假如某個(gè) key 是觸發(fā) error 的元兇,那么就有可能觸發(fā)二次 error 的情況:
-
xxxKey觸發(fā)了 error,組件報(bào)錯(cuò) - 組件報(bào)錯(cuò)導(dǎo)致
resetKeys里的一些東西改了 -
componentDidUpdate發(fā)現(xiàn)resetKeys里有東西更新了,不廢話,馬上重置 - 重置完了,顯示報(bào)錯(cuò)的組件,因?yàn)?error 還存在(或者還未解決),報(bào)錯(cuò)的組件又再次觸發(fā)了 error
- ...
所以要區(qū)分出來(lái)這一次到底是因?yàn)?error 才 render 還是普通組件的 render,而且還需要確保當(dāng)前有錯(cuò)誤才重置,都沒(méi)錯(cuò)誤還重置個(gè)毛。具體實(shí)現(xiàn)思路如圖所示:

實(shí)現(xiàn)如下
class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
state = initialState;
// 是否已經(jīng)由于 error 而引發(fā)的 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;
// 已經(jīng)存在錯(cuò)誤,并且是第一次由于 error 而引發(fā)的 render/update,那么設(shè)置 flag=true,不會(huì)重置
if (error !== null && !this.updatedWithError) {
this.updatedWithError = true;
return;
}
// 已經(jīng)存在錯(cuò)誤,并且是普通的組件 render,則檢查 resetKeys 是否有改動(dòng),改了就重置
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() {
...
}
}
上面的改動(dòng)有:
- 用
updatedWithError作為 flag 判斷是否已經(jīng)由于 error 出現(xiàn)而引發(fā)的 render/update - 如果當(dāng)前沒(méi)有錯(cuò)誤,無(wú)論如何都不會(huì)重置
- 每次更新:當(dāng)前存在錯(cuò)誤,且第一次由于 error 出現(xiàn)而引發(fā)的 render/update,則設(shè)置
updatedWithError = true,不會(huì)重置狀態(tài) - 每次更新:當(dāng)前存在錯(cuò)誤,且如果
updatedWithError為true說(shuō)明已經(jīng)由于 error 而更新過(guò)了,以后的更新只要resetKeys里的東西改了,都會(huì)被重置
至此,我們擁有了兩種可以實(shí)現(xiàn)重置的方式了:
| 方法 | 觸發(fā)范圍 | 使用場(chǎng)景 | 思想負(fù)擔(dān) |
|---|---|---|---|
| 手動(dòng)調(diào)用 resetErrorBoundary | 一般在 fallback 組件里 | 用戶可以在 fallback 里手動(dòng)點(diǎn)擊“重置”實(shí)現(xiàn)重置 | 最直接,思想負(fù)擔(dān)較輕 |
| 更新 resetKeys | 哪里都行,范圍更廣 | 用戶可以在報(bào)錯(cuò)組件外部重置、resetKeys 里有報(bào)錯(cuò)組件依賴(lài)的數(shù)據(jù)、渲染時(shí)自動(dòng)重置 |
間接觸發(fā),要思考哪些值放到 resetKeys 里,思想負(fù)擔(dān)較重 |
總結(jié)這一鞭的改動(dòng):
1. 添加 resetKeys 和 onResetKeysChange 兩個(gè) props,為開(kāi)發(fā)者提供監(jiān)聽(tīng)值變化而自動(dòng)重置的功能
2. 在 componentDidUpdate 里,只要不是由于 error 引發(fā)的組件渲染或更新,而且 resetKeys 有變化了,那么直接重置組件狀態(tài)來(lái)達(dá)到自動(dòng)重置
這里自動(dòng)重置還有一個(gè)好處:假如是由于網(wǎng)絡(luò)波動(dòng)引發(fā)的異常,那頁(yè)面當(dāng)然會(huì)顯示 fallback 了,如果用上面直接調(diào)用 props.resetErrorBoundary 方法來(lái)重置,只要用戶不點(diǎn)“重置”按鈕,那塊地方永遠(yuǎn)不會(huì)被重置。又由于是因?yàn)榫W(wǎng)絡(luò)波動(dòng)引發(fā)的異常,有可能就那0.001 秒有問(wèn)題,別的時(shí)間又好了,所以如果我們將一些變化頻繁的值放到 resetKeys 里就很容易自動(dòng)觸發(fā)重置。例如,報(bào)錯(cuò)后,其它地方的值變了從而更改了 resetKeys 的元素值就會(huì)觸發(fā)自動(dòng)重置。對(duì)于用戶來(lái)說(shuō),最多只會(huì)看到一閃而過(guò)的 fallback,然后那塊地方又正常了。這樣一來(lái),用戶也不需要親自觸發(fā)重置了。
第五鞭:輸出輪子
上面四鞭里,到最后都是 export default ErrorBoundary 將組件輸出,如果代理里很多個(gè)地方都要 catch error,就有這樣很啰嗦的代碼:
<div>
<ErrorBoundary>
<AAA/>
</ErrorBoundary>
<ErrorBoundary>
<BBB/>
</ErrorBoundary>
<ErrorBoundary>
<CCC/>
</ErrorBoundary>
<ErrorBoundary>
<DDD/>
</ErrorBoundary>
</div>
要處理這樣啰嗦的包裹,可以借鑒 React Router 的 withRouter 函數(shù),我們也可以輸出一個(gè)高階函數(shù) withErrorBoundary :
/**
* with 寫(xiě)法
* @param Component 業(yè)務(wù)組件
* @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;
}
使用的時(shí)候就更簡(jiǎn)潔了一些了:
// 業(yè)務(wù)子組件
const User = () => {
return <div>User</div>
}
// 在業(yè)務(wù)組件加一層 ErrorBoundary
const UserWithErrorBoundary = withErrorBoundary(User, {
onError: () => logger.error('出錯(cuò)啦'),
onReset: () => console.log('已重置')
})
// 業(yè)務(wù)父組件
const App = () => {
return (
<div>
<UserWithErrorBoundary/>
</div>
)
}
其實(shí) withXXX 這種寫(xiě)法還可以寫(xiě)成裝飾器,將 @withXXX 放到 class component 上也很方便,但是對(duì)于 functional component 就放不了了,有點(diǎn)受限,這里不展開(kāi)了。
還有沒(méi)有更好的設(shè)計(jì)呢?我們觀察到只有一些比較“嚴(yán)重的異常”瀏覽器才會(huì)報(bào)錯(cuò),比如開(kāi)頭提到的 TypeError: xxx is not a function。JS 是個(gè)動(dòng)態(tài)類(lèi)型語(yǔ)言,在瀏覽器里你可以:NaN + 1,可以 NaN.toString(),可以 '1' + 1 都不報(bào)任何錯(cuò)誤。其實(shí)官網(wǎng)也說(shuō)了,對(duì)于一些錯(cuò)誤 componenDidCatch 是不能自動(dòng)捕獲的:

不過(guò),這些錯(cuò)誤在代碼里開(kāi)發(fā)者其實(shí)是知道的呀。既然開(kāi)發(fā)者們有辦法拿到這些錯(cuò)誤,那把錯(cuò)誤直接拋出就可以讓 ErrorBoundary catch 到了:
- 有錯(cuò)誤的時(shí)候,開(kāi)發(fā)者自己調(diào)用
handleError(error)將錯(cuò)誤傳入函數(shù)中 -
handleError將錯(cuò)誤throw new Error(error) - ErrorBoundary 發(fā)現(xiàn)有上面拋出的 Error,調(diào)用
componentDidCatch處理錯(cuò)誤 - ...
我來(lái)提供一種使用 React Hook 的實(shí)現(xiàn)方式:
/**
* 自定義錯(cuò)誤的 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; // 初始有錯(cuò)誤時(shí),直接拋出
if (error) throw error; // 后來(lái)再有錯(cuò)誤,也直接拋出
return setError; // 返回開(kāi)發(fā)者可手動(dòng)設(shè)置錯(cuò)誤的鉤子
}
使用上面的 hook,對(duì)于一些需要自己處理的錯(cuò)誤,可以有兩種處理方法:
-
const handleError = useErrorHandler(),然后handleError(yourError) -
useErrorHandler(otherHookError),如果別的 hooks 里有 export error,完全可以直接將這個(gè) 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, // 開(kāi)發(fā)者自己處理錯(cuò)誤,將錯(cuò)誤拋出
)
}
return greeting ? (
<div>{greeting}</div>
) : (
<form onSubmit={handleSubmit}>
<label>Name</label>
<input id="name" />
<button type="submit">get a greeting</button>
</form>
)
}
// 用 ErrorBoundary 包裹,處理手動(dòng)拋出的錯(cuò)誤
export default withErrorBoundary(Greeting)
或者:
function Greeting() {
const [name, setName] = React.useState('')
const {greeting, error} = useGreeting(name)
// 開(kāi)發(fā)者自己處理錯(cuò)誤,將錯(cuò)誤拋出
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 包裹,處理手動(dòng)拋出的錯(cuò)誤
export default withErrorBoundary(Greeting)
總結(jié):
1. 提供 withErrorBoundary 方法來(lái)包裹業(yè)務(wù)組件實(shí)現(xiàn)異常捕獲
2. 提供 useErrorHandler hook 讓開(kāi)發(fā)者自己處理/拋出錯(cuò)誤
“閃電五連鞭”總結(jié)
再次總結(jié)一下“抓錯(cuò)五連鞭”的要點(diǎn):
- 造一個(gè) ErrorBoundary 輪子
-
componentDidCatch捕獲頁(yè)面報(bào)錯(cuò),getDerivedStateFromError更新 ErrorBoundary 的 state,并獲取具體 error - 提供多種展示錯(cuò)誤內(nèi)容入口:
fallback,FallbackComponent,fallbackRender - 重置鉤子:提供
onReset,resetErrorBoundary的傳值和調(diào)用,以實(shí)現(xiàn)重置 - 重置監(jiān)聽(tīng)數(shù)組:監(jiān)聽(tīng)
resetKeys的變化來(lái)重置。對(duì)于擁有復(fù)雜元素的resetKeys數(shù)組提供onResetKeysChange讓開(kāi)發(fā)者自行判斷。在componentDidUpdate里監(jiān)聽(tīng)每次渲染時(shí)resetKeys變化,并設(shè)置updatedWithError作為 flag 判斷是否由于 error 引發(fā)的渲染,對(duì)于普通渲染,只要resetKeys變化,直接重置 - 提供 ErrorBoundary 的2種使用方法:嵌套業(yè)務(wù)組件,將業(yè)務(wù)組件傳入
withErrorBoundary高階函數(shù)。提供useErrorBoundary鉤子給開(kāi)發(fā)者自己拋出 ErrorBoundary 不能自動(dòng)捕獲的錯(cuò)誤
耗子尾汁,好好反思
打完了這一套“五連鞭”,再次發(fā)布上線,一切OK。
然后我找到這位后端,跟他說(shuō)了線上事故。當(dāng)時(shí)他就流眼淚了,捂著臉,兩分多鐘以后,就好了。
我說(shuō):小伙子,你不講碼德你不懂。他說(shuō):對(duì)不起,我不懂規(guī)矩。后來(lái)他說(shuō)他寫(xiě)了好幾年動(dòng)態(tài)語(yǔ)言,啊,看來(lái)是有 bear 來(lái)。這個(gè)年輕人不講碼德。來(lái)!騙!來(lái)!偷襲我一個(gè)24歲小前端,這好嗎?這不好,我勸,這位后端,耗子尾汁,好好反思,以后不要搞這樣的聰明,小聰明。程序猿要以和為貴,要講碼德,不要搞窩里斗。
謝謝朋友們。
(故事純屬虛構(gòu),如有雷同,請(qǐng)自我檢討或者一鍵三連)