All files / src/form/dashboard WidgetErrorBoundary.tsx

9.09% Statements 1/11
0% Branches 0/2
0% Functions 0/4
9.09% Lines 1/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40                          6x                                                    
import React, { ErrorInfo, ReactNode } from "react";
import { DashboardWidgetProps, WidgetDataResponseProps } from "@props/RecordProps";
import { Alert } from "antd";
 
export class WidgetErrorBoundary extends React.Component<{
  widget: DashboardWidgetProps;
  dataAndConfigs: WidgetDataResponseProps;
}, { hasError: boolean }> {
  constructor(props: Readonly<{ widget: DashboardWidgetProps; dataAndConfigs: WidgetDataResponseProps; }>) {
    super(props);
    this.state = { hasError: false };
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  static getDerivedStateFromError = (error: unknown): { hasError: boolean } => {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true };
  };
 
  componentDidCatch = (error: Error, errorInfo: ErrorInfo): void => {
    console.error("error: ", error);
    console.error("errorInfo: ", errorInfo);
  };
 
  render(): ReactNode {
    if (this.state.hasError) {
      // 你可以自定义降级后的 UI 并渲染
      const message = `Failed to render widget[${JSON.stringify(this.props.widget)}] with dataAndConfig [${JSON.stringify(this.props.dataAndConfigs)}]`;
      return (<Alert
        message="Failed to render widget"
        description={message}
        type="error"
        className="light-bg-alert"
        showIcon
      />);
    }
 
    return this.props.children;
  }
}