error.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 { 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. try {
  24. downloadAs(
  25. JSON.stringify(localStorage),
  26. "chatgpt-next-web-snapshot.json",
  27. );
  28. } finally {
  29. localStorage.clear();
  30. location.reload();
  31. }
  32. }
  33. render() {
  34. if (this.state.hasError) {
  35. // Render error message
  36. return (
  37. <div className="error">
  38. <h2>Oops, something went wrong!</h2>
  39. <pre>
  40. <code>{this.state.error?.toString()}</code>
  41. <code>{this.state.info?.componentStack}</code>
  42. </pre>
  43. <div style={{ display: "flex", justifyContent: "space-between" }}>
  44. <a href={ISSUE_URL} className="report">
  45. <IconButton
  46. text="Report This Error"
  47. icon={<GithubIcon />}
  48. bordered
  49. />
  50. </a>
  51. <IconButton
  52. icon={<ResetIcon />}
  53. text="Clear All Data"
  54. onClick={() =>
  55. confirm(Locale.Settings.Actions.ConfirmClearAll) &&
  56. this.clearAndSaveData()
  57. }
  58. bordered
  59. />
  60. </div>
  61. </div>
  62. );
  63. }
  64. // if no error occurred, render children
  65. return this.props.children;
  66. }
  67. }