error.tsx 2.0 KB

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