error.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 (
  57. await showConfirm(Locale.Settings.Actions.ConfirmClearAll)
  58. ) {
  59. this.clearAndSaveData();
  60. }
  61. }}
  62. bordered
  63. />
  64. </div>
  65. </div>
  66. );
  67. }
  68. // if no error occurred, render children
  69. return this.props.children;
  70. }
  71. }