errorHandler.tsx 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import * as React from 'react';
  2. import RouteError from 'sentry/views/routeError';
  3. type State = {
  4. error: Error | undefined;
  5. hasError: boolean;
  6. };
  7. export default function errorHandler<P>(Component: React.ComponentType<P>) {
  8. class ErrorHandler extends React.Component<P, State> {
  9. static getDerivedStateFromError(error: Error) {
  10. // Update state so the next render will show the fallback UI.
  11. return {
  12. hasError: true,
  13. error,
  14. };
  15. }
  16. state: State = {
  17. // we are explicit if an error has been thrown since errors thrown are not guaranteed
  18. // to be truthy (e.g. throw null).
  19. hasError: false,
  20. error: undefined,
  21. };
  22. componentDidCatch(_error: Error, info: React.ErrorInfo) {
  23. // eslint-disable-next-line no-console
  24. console.error(
  25. 'Component stack trace caught in <ErrorHandler />:',
  26. info.componentStack
  27. );
  28. }
  29. render() {
  30. if (this.state.hasError) {
  31. return <RouteError error={this.state.error} />;
  32. }
  33. return <Component {...this.props} />;
  34. }
  35. }
  36. return ErrorHandler;
  37. }