React 16及以上版本引入了错误边界,它是专门用于捕获子组件树中错误的React组件。
Error Boundary组件必须实现componentDidCatch
生命周期方法或使用static getDerivedStateFromError
方法。
// ErrorBoundary.js
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// 更新状态以显示降级UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// 可以将错误日志发送到服务端
console.log('Error:', error);
console.log('Error Info:', errorInfo);
}
render() {
if (this.state.hasError) {
// 你可以渲染任何自定义的降级UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
在应用中使用Error Boundary组件:
// App.js
import React from 'react';
import ErrorBoundary from './ErrorBoundary';
import SomeComponent from './SomeComponent';
function App() {
return (
<ErrorBoundary>
<SomeComponent />
</ErrorBoundary>
);
}
export default App;
try-catch
语句对于在事件处理函数或异步代码中捕获错误,可以使用try-catch
语句。
function handleClick() {
try {
// 可能会抛出错误的代码
someFunctionThatMightThrow();
} catch (error) {
// 处理错误
console.error('Error caught:', error);
}
}
Error
对象在组件内部,你可以手动抛出和捕获错误,通常用于调试或处理特定条件下的错误。
function SomeComponent() {
const handleClick = () => {
try {
if (someCondition) {
throw new Error('Something went wrong');
}
} catch (error) {
console.error('Error caught:', error);
}
};
return <button onClick={handleClick}>Click Me</button>;
}
componentDidCatch
生命周期方法对于类组件,可以直接在组件中实现componentDidCatch
方法。
class SomeComponent extends React.Component {
componentDidCatch(error, errorInfo) {
// 处理错误
console.log('Error:', error);
console.log('Error Info:', errorInfo);
}
render() {
// 渲染逻辑
}
}
React Error Boundary库提供了一些高级功能,如自动错误报告和错误恢复。
// 安装库
// npm install react-error-boundary
import { ErrorBoundary } from 'react-error-boundary';
function ErrorFallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
function App() {
return (
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => {
// 重置逻辑
}}
>
<SomeComponent />
</ErrorBoundary>
);
}
对于全局错误处理,可以使用window.onerror和window.onunhandledrejection来捕获未处理的错误和未捕获的Promise拒绝。
window.onerror = function (message, source, lineno, colno, error) {
console.error('Global Error:', { message, source, lineno, colno, error });
};
window.onunhandledrejection = function (event) {
console.error('Unhandled Rejection:', event.reason);
};
try-catch
语句:用于捕获事件处理函数和异步代码中的错误。Error
对象:用于手动抛出和捕获错误。componentDidCatch
方法:用于类组件中的错误捕获。根据不同的错误捕获需求,选择合适的方式可以提高应用的稳定性和用户体验。