error.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use client";
  2. import React from "react";
  3. import { IconButton } from "./button";
  4. import ResetIcon from "../icons/reload.svg";
  5. import Locale from "../locales";
  6. import { showConfirm } from "./ui-lib";
  7. import { useSyncStore } from "../store/sync";
  8. import { useChatStore } from "../store/chat";
  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. useChatStore.getState().clearAllData();
  28. }
  29. }
  30. render() {
  31. if (this.state.hasError) {
  32. // Render error message
  33. return (
  34. <div className="error">
  35. <h2>Oops, something went wrong!</h2>
  36. <pre>
  37. <code>{this.state.error?.toString()}</code>
  38. <code>{this.state.info?.componentStack}</code>
  39. </pre>
  40. <div style={{ display: "flex", justifyContent: "center" }}>
  41. <IconButton
  42. icon={<ResetIcon />}
  43. text="Clear All Data"
  44. onClick={async () => {
  45. if (await showConfirm(Locale.Settings.Danger.Reset.Confirm)) {
  46. this.clearAndSaveData();
  47. }
  48. }}
  49. bordered
  50. />
  51. </div>
  52. </div>
  53. );
  54. }
  55. // if no error occurred, render children
  56. return this.props.children;
  57. }
  58. }