error.tsx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. interface IErrorBoundaryState {
  7. hasError: boolean;
  8. error: Error | null;
  9. info: React.ErrorInfo | null;
  10. }
  11. export class ErrorBoundary extends React.Component<any, IErrorBoundaryState> {
  12. constructor(props: any) {
  13. super(props);
  14. this.state = { hasError: false, error: null, info: null };
  15. }
  16. componentDidCatch(error: Error, info: React.ErrorInfo) {
  17. // Update state with error details
  18. this.setState({ hasError: true, error, info });
  19. }
  20. clearAndSaveData() {
  21. // 直接清除数据,不下载备份
  22. localStorage.clear();
  23. location.reload();
  24. }
  25. render() {
  26. if (this.state.hasError) {
  27. // Render error message
  28. return (
  29. <div className="error">
  30. <h2>Oops, something went wrong!</h2>
  31. <pre>
  32. <code>{this.state.error?.toString()}</code>
  33. <code>{this.state.info?.componentStack}</code>
  34. </pre>
  35. <div style={{ display: "flex", justifyContent: "center" }}>
  36. <IconButton
  37. icon={<ResetIcon />}
  38. text="Clear All Data"
  39. onClick={() => {
  40. this.clearAndSaveData();
  41. }}
  42. bordered
  43. />
  44. </div>
  45. </div>
  46. );
  47. }
  48. // if no error occurred, render children
  49. return this.props.children;
  50. }
  51. }