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. import { useChatStore } from "../store/chat";
  11. interface IErrorBoundaryState {
  12. hasError: boolean;
  13. error: Error | null;
  14. info: React.ErrorInfo | null;
  15. }
  16. export class ErrorBoundary extends React.Component<any, IErrorBoundaryState> {
  17. constructor(props: any) {
  18. super(props);
  19. this.state = { hasError: false, error: null, info: null };
  20. }
  21. componentDidCatch(error: Error, info: React.ErrorInfo) {
  22. // Update state with error details
  23. this.setState({ hasError: true, error, info });
  24. }
  25. clearAndSaveData() {
  26. try {
  27. useSyncStore.getState().export();
  28. } finally {
  29. useChatStore.getState().clearAllData();
  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. }