|
| 1 | +## react错误捕获 |
| 2 | +React16开始,官方提供ErrorBoundary错误边界,被该组件包裹的子组件render函数报错时会触发离当前组件最近的父组件ErrorBoundary |
| 3 | + |
| 4 | +这种情况下,可以通过componentDidCatch将捕获的错误上报 |
| 5 | + |
| 6 | +``` |
| 7 | +import React, { ReactNode } from 'react' |
| 8 | +import { lazyReportBatch } from '../common/report' |
| 9 | +import { |
| 10 | + getErrorUid, |
| 11 | + getReactComponentInfo, |
| 12 | + parseStackFrames |
| 13 | +} from '../common/utils' |
| 14 | +import { ReactErrorType } from '../types' |
| 15 | +import { TraceSubTypeEnum, TraceTypeEnum } from '../common/enum' |
| 16 | +import { getBehaviour, getRecordScreenData } from '../behavior' |
| 17 | +
|
| 18 | +interface ErrorBoundaryProps { |
| 19 | + Fallback: ReactNode // ReactNode 表示任意有效的 React 内容 |
| 20 | + children: ReactNode |
| 21 | +} |
| 22 | +
|
| 23 | +interface ErrorBoundaryState { |
| 24 | + hasError: boolean |
| 25 | +} |
| 26 | +
|
| 27 | +let err = {} |
| 28 | +
|
| 29 | +class ErrorBoundary extends React.Component< |
| 30 | + ErrorBoundaryProps, |
| 31 | + ErrorBoundaryState |
| 32 | +> { |
| 33 | + state: ErrorBoundaryState = { hasError: false } |
| 34 | +
|
| 35 | + componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { |
| 36 | + this.setState({ hasError: true }) |
| 37 | + const { componentName, url: src } = getReactComponentInfo(errorInfo) |
| 38 | + const type = TraceTypeEnum.error |
| 39 | + const subType = TraceSubTypeEnum.react |
| 40 | + const message = error.message |
| 41 | + const stack = parseStackFrames(error) |
| 42 | + const pageUrl = window.location.href |
| 43 | + const errId = getErrorUid(`${subType}-${message}-${src}`) |
| 44 | + const info = error.message |
| 45 | + const behavior = getBehaviour() |
| 46 | + const state = behavior?.breadcrumbs?.state || [] |
| 47 | + const eventData = getRecordScreenData() |
| 48 | + const reportData: ReactErrorType = { |
| 49 | + type, |
| 50 | + subType, |
| 51 | + stack, |
| 52 | + pageUrl, |
| 53 | + message, |
| 54 | + errId, |
| 55 | + componentName, |
| 56 | + info, |
| 57 | + src, |
| 58 | + state, |
| 59 | + timestamp: new Date().getTime(), |
| 60 | + eventData |
| 61 | + } |
| 62 | + err = reportData |
| 63 | + lazyReportBatch(reportData) |
| 64 | + } |
| 65 | +
|
| 66 | + render() { |
| 67 | + const { Fallback } = this.props |
| 68 | + if (this.state.hasError) { |
| 69 | + // @ts-ignore |
| 70 | + return <Fallback error={err}/> |
| 71 | + } |
| 72 | +
|
| 73 | + return this.props.children |
| 74 | + } |
| 75 | +} |
| 76 | +
|
| 77 | +export default ErrorBoundary |
| 78 | +
|
| 79 | +``` |
0 commit comments