ErrorBoudary.jsx 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. /**
  4. * @see https://reactjs.org/docs/error-boundaries.html
  5. */
  6. class ErrorBoundary extends React.Component {
  7. constructor(props) {
  8. super(props);
  9. this.state = { error: null, errorInfo: null };
  10. }
  11. componentDidCatch(error, errorInfo) {
  12. // You can also log the error to an error reporting service
  13. // logErrorToMyService(error, errorInfo);
  14. // Catch errors in any components below and re-render with error message
  15. this.setState({
  16. error,
  17. errorInfo,
  18. });
  19. }
  20. render() {
  21. const { error, errorInfo } = this.state;
  22. if (errorInfo != null) {
  23. // split componetStack
  24. // see https://regex101.com/r/Uc448G/1
  25. const firstStack = errorInfo.componentStack.split(/\s*in\s/)[1];
  26. return (
  27. <div className="card border-danger">
  28. <div className="card-header">Error occured in {firstStack}</div>
  29. <div className="card-body">
  30. <h5>{error && error.toString()}</h5>
  31. <details className="card bg-light small mb-0" style={{ whiteSpace: 'pre-wrap' }}>
  32. {errorInfo.componentStack}
  33. </details>
  34. </div>
  35. </div>
  36. );
  37. }
  38. // Normally, just render children
  39. return this.props.children;
  40. }
  41. }
  42. ErrorBoundary.propTypes = {
  43. children: PropTypes.object,
  44. };
  45. export default ErrorBoundary;