antd-pro的项目使用了Sentry做错误收集,遇到个问题。antd-pro自身加了错误边界,导致页面加载过程的错误没法被捕获(本地可以,线上不行)。使用create-react-app搭建的项目也是可以正常捕获的。解决思路一个是把antd-pro的错误边界去掉,另一个是把错误拦截再手动抛给Sentry。
方法一:关闭antd-pro的错误捕获。有个缺点是线上时候如果报错会白屏,体验不太好。不推荐。
config->defaultSettings.ts->ErrorBoundary:false
方法二:考虑在页面外边包一个layout,在这个里边捕获错误外抛。首先尝试在routes中利用嵌套路由,不生效。然后找到一个方法app->layout中的childrenRender,这个方法本来是做路由守卫的,也能在页面渲染前拦截处理并重新渲染。
import ErrorBoundary from '@/components/ErrorBoundary';export const layout: RunTimeLayoutConfig = ({ initialState }) => { return { childrenRender: (children, props) => { return <ErrorBoundary> {children} </ErrorBoundary> },
}
}
ErrorBoundary:
import React from 'react';import * as Sentry from '@sentry/react';// type FallbackRender = (props: { error: Error | null }) => React.ReactElement;// export class ErrorBoundary extends Component<React.PropsWithChildren<{ fallbackRender: FallbackRender }>, any>{export default class ErrorBoundary extends React.Component { state = { error: null } // 捕捉错误,改变 error 的状态 static getDerivedStateFromError(error: Error) { // 把错误发送给Sentry Sentry.captureException(error); return { error } } // 不走这个钩子函数 // componentDidCatch(error, errorInfo) { // // 你同样可以将错误日志上报给服务器 // // logErrorToMyService(error, errorInfo); // console.log(error, errorInfo, 'errorInfoerrorInfo') // } render() { // const { error } = this.state; // const { fallbackRender, children } = this.props; const { children } = this.props as any; // console.log(this.props ,error, 'childrenchildren') // if (error) { // return fallbackRender(error); // } return children; }}// 使用错误边界组件// <ErrorBoundary fallbackRender={/*某个备用UI组件*/}>// <App />// </ErrorBoundary>
可以正常捕获错误了。
参考文章:
procomponents官网:procomponents.ant.design/components/…
错误边界描述:zhuanlan.zhihu.com/p/621339091…
嵌套菜单:blog.csdn.net/qq_40319394…
动态路由childrenRender:blog.csdn.net/haiyabtx/ar…
错误边界参考:blog.csdn.net/m0_65121454…