Advertisement
minafaw3

ErrorBoundary

Nov 11th, 2024
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. /* eslint-disable react/jsx-no-literals */
  2. import React, { Component, ReactNode } from 'react';
  3.  
  4. interface ErrorBoundaryProps {
  5. children: ReactNode;
  6. }
  7.  
  8. interface ErrorBoundaryState {
  9. hasError: boolean;
  10. error: Error | null;
  11. }
  12.  
  13. class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  14. constructor(props: ErrorBoundaryProps) {
  15. super(props);
  16. this.state = {
  17. hasError: false,
  18. error: null,
  19. };
  20. }
  21.  
  22. static getDerivedStateFromError(error: Error): ErrorBoundaryState {
  23. return { hasError: true, error };
  24. }
  25.  
  26. componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
  27. console.error('ErrorBoundary caught an error', error, errorInfo);
  28. }
  29.  
  30. render() {
  31. const { hasError, error } = this.state;
  32. const { children } = this.props;
  33. if (hasError && error) {
  34. return (
  35. <div>
  36. <h1>Something went wrong.</h1>
  37. <p>{error.message}</p>
  38. </div>
  39. );
  40. }
  41.  
  42. return children;
  43. }
  44. }
  45.  
  46. export default ErrorBoundary;
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement