index.tsx 983 B

123456789101112131415161718192021222324252627282930313233343536
  1. import type { ErrorInfo } from 'react';
  2. import React from 'react';
  3. import ErrorFallback from '../error-fallback';
  4. interface ErrorBoundaryProps {
  5. FallbackComponent?: any;
  6. }
  7. interface ErrorBoundaryState {
  8. hasError: any;
  9. error: any;
  10. errorInfo: string;
  11. }
  12. class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
  13. static getDerivedStateFromError(error: Error) {
  14. return { hasError: true, error: error, errorInfo: error.message };
  15. }
  16. state = { hasError: false, error: null, errorInfo: '' };
  17. componentDidCatch(error: any, errorInfo: ErrorInfo) {
  18. console.log(error, errorInfo);
  19. }
  20. render() {
  21. const { children, FallbackComponent = ErrorFallback } = this.props;
  22. const { error, errorInfo } = this.state;
  23. if (this.state.hasError) {
  24. return <FallbackComponent error={error} errorInfo={errorInfo} />;
  25. }
  26. return children;
  27. }
  28. }
  29. export default ErrorBoundary;