error.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import React from "react";
  2. import { IconButton } from "./button";
  3. import GithubIcon from "../icons/github.svg";
  4. import ResetIcon from "../icons/reload.svg";
  5. import { ISSUE_URL } from "../constant";
  6. import Locale from "../locales";
  7. import { showConfirm } from "./ui-lib";
  8. import { useSyncStore } from "../store/sync";
  9. interface IErrorBoundaryState {
  10. hasError: boolean;
  11. error: Error | null;
  12. info: React.ErrorInfo | null;
  13. }
  14. export class ErrorBoundary extends React.Component<any, IErrorBoundaryState> {
  15. constructor(props: any) {
  16. super(props);
  17. this.state = { hasError: false, error: null, info: null };
  18. }
  19. componentDidCatch(error: Error, info: React.ErrorInfo) {
  20. // Update state with error details
  21. this.setState({ hasError: true, error, info });
  22. }
  23. clearAndSaveData() {
  24. try {
  25. useSyncStore.getState().export();
  26. } finally {
  27. localStorage.clear();
  28. location.reload();
  29. }
  30. }
  31. render() {
  32. if (this.state.hasError) {
  33. // Render error message
  34. return (
  35. <div className="error">
  36. <h2>Oops, something went wrong!</h2>
  37. <pre>
  38. <code>{this.state.error?.toString()}</code>
  39. <code>{this.state.info?.componentStack}</code>
  40. </pre>
  41. <div style={{ display: "flex", justifyContent: "space-between" }}>
  42. <a href={ISSUE_URL} className="report">
  43. <IconButton
  44. text="Report This Error"
  45. icon={<GithubIcon />}
  46. bordered
  47. />
  48. </a>
  49. <IconButton
  50. icon={<ResetIcon />}
  51. text="Clear All Data"
  52. onClick={async () => {
  53. if (await showConfirm(Locale.Settings.Danger.Reset.Confirm)) {
  54. this.clearAndSaveData();
  55. }
  56. }}
  57. bordered
  58. />
  59. </div>
  60. </div>
  61. );
  62. }
  63. // if no error occurred, render children
  64. return this.props.children;
  65. }
  66. }