error.tsx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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, StoreKey } from "../constant";
  6. import Locale from "../locales";
  7. import { downloadAs } from "../utils";
  8. interface IErrorBoundaryState {
  9. hasError: boolean;
  10. error: Error | null;
  11. info: React.ErrorInfo | null;
  12. }
  13. export class ErrorBoundary extends React.Component<any, IErrorBoundaryState> {
  14. constructor(props: any) {
  15. super(props);
  16. this.state = { hasError: false, error: null, info: null };
  17. }
  18. componentDidCatch(error: Error, info: React.ErrorInfo) {
  19. // Update state with error details
  20. this.setState({ hasError: true, error, info });
  21. }
  22. clearAndSaveData() {
  23. const snapshot: Record<string, any> = {};
  24. Object.values(StoreKey).forEach((key) => {
  25. snapshot[key] = localStorage.getItem(key);
  26. if (snapshot[key]) {
  27. try {
  28. snapshot[key] = JSON.parse(snapshot[key]);
  29. } catch {}
  30. }
  31. });
  32. try {
  33. downloadAs(JSON.stringify(snapshot), "chatgpt-next-web-snapshot.json");
  34. } catch {}
  35. localStorage.clear();
  36. }
  37. render() {
  38. if (this.state.hasError) {
  39. // Render error message
  40. return (
  41. <div className="error">
  42. <h2>Oops, something went wrong!</h2>
  43. <pre>
  44. <code>{this.state.error?.toString()}</code>
  45. <code>{this.state.info?.componentStack}</code>
  46. </pre>
  47. <div style={{ display: "flex", justifyContent: "space-between" }}>
  48. <a href={ISSUE_URL} className="report">
  49. <IconButton
  50. text="Report This Error"
  51. icon={<GithubIcon />}
  52. bordered
  53. />
  54. </a>
  55. <IconButton
  56. icon={<ResetIcon />}
  57. text="Clear All Data"
  58. onClick={() =>
  59. confirm(Locale.Store.ConfirmClearAll) && this.clearAndSaveData()
  60. }
  61. bordered
  62. />
  63. </div>
  64. </div>
  65. );
  66. }
  67. // if no error occurred, render children
  68. return this.props.children;
  69. }
  70. }