自定义错误类与错误边界(React)
请设计一个自定义错误类层次体系,并实现React错误边界(Error Boundary)组件来捕获和处理渲染错误。
回答
孤独的心
class AppError extends Error {
constructor(message, code, cause) {
super(message, { cause });
this.name = 'AppError';
this.code = code;
this.timestamp = Date.now();
}
toJSON() {
return { name: this.name, message: this.message, code: this.code, cause: this.cause };
}
}
class NetworkError extends AppError {
constructor(message, statusCode, cause) {
super(message, `NET_${statusCode}`, cause);
this.name = 'NetworkError';
this.statusCode = statusCode;
}
}
class ValidationError extends AppError {
constructor(field, message) {
super(message, 'VAL_001');
this.name = 'ValidationError';
this.field = field;
}
}
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
reportError({ error: error.toString(), info: errorInfo });
}
render() {
if (this.state.hasError) {
return this.props.fallback?.(this.state.error, () => this.setState({ hasError: false }))
|| <div>出错了: {this.state.error?.message}</div>;
}
return this.props.children;
}
}
要点:getDerivedStateFromError和componentDidCatch是React错误边界的两个生命周期钩子。