From a92d556486d3eecee9e260a656cb9f871fb068aa Mon Sep 17 00:00:00 2001 From: zdl <3489966805@qq.com> Date: Fri, 24 Oct 2025 16:28:47 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=B0=83=E6=95=B4=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/ErrorBoundary.js | 63 ++++++++++++++++----------------- 1 file changed, 31 insertions(+), 32 deletions(-) diff --git a/src/components/ErrorBoundary.js b/src/components/ErrorBoundary.js index ba808f55..c8e72484 100755 --- a/src/components/ErrorBoundary.js +++ b/src/components/ErrorBoundary.js @@ -18,31 +18,21 @@ class ErrorBoundary extends React.Component { } static getDerivedStateFromError(error) { - // 开发环境:不拦截错误,让 React DevTools 显示完整堆栈 - if (process.env.NODE_ENV === 'development') { - return { hasError: false }; - } - // 生产环境:拦截错误,显示友好界面 + // 所有环境都捕获错误,避免无限重渲染 return { hasError: true }; } componentDidCatch(error, errorInfo) { - // 开发环境:打印错误到控制台,但不显示错误边界 - if (process.env.NODE_ENV === 'development') { - logger.error('ErrorBoundary', 'componentDidCatch', error, { - componentStack: errorInfo.componentStack, - developmentMode: true - }); - // 不更新 state,让错误继续抛出 - return; - } - - // 生产环境:保存错误信息到 state - logger.error('ErrorBoundary', 'componentDidCatch', error, { + // 记录详细的错误日志 + logger.error('ErrorBoundary', 'Component Error Caught', error, { componentStack: errorInfo.componentStack, - productionMode: true + errorName: error.name, + errorMessage: error.message, + environment: process.env.NODE_ENV, + stack: error.stack }); + // 保存错误信息到 state this.setState({ error: error, errorInfo: errorInfo @@ -50,12 +40,7 @@ class ErrorBoundary extends React.Component { } render() { - // 开发环境:直接渲染子组件,不显示错误边界 - if (process.env.NODE_ENV === 'development') { - return this.props.children; - } - - // 生产环境:如果有错误,显示错误边界 + // 如果有错误,显示错误边界(所有环境) if (this.state.hasError) { return ( @@ -67,31 +52,45 @@ class ErrorBoundary extends React.Component { 页面出现错误! - 页面加载时发生了未预期的错误,请尝试刷新页面。 + {process.env.NODE_ENV === 'development' + ? '组件渲染时发生错误,请查看下方详情和控制台日志。' + : '页面加载时发生了未预期的错误,请尝试刷新页面。'} - {process.env.NODE_ENV === 'development' && ( + {/* 开发环境显示详细错误信息 */} + {process.env.NODE_ENV === 'development' && this.state.error && ( - 错误详情: - - {this.state.error && this.state.error.toString()} - {this.state.errorInfo && this.state.errorInfo.componentStack} + 错误详情: + + {this.state.error.name}: {this.state.error.message} + {this.state.error.stack && ( + {this.state.error.stack} + )} + {this.state.errorInfo && this.state.errorInfo.componentStack && ( + <> + 组件堆栈: + {this.state.errorInfo.componentStack} + + )} )}