error.tsx 2.0 KB

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