UNPKG

@grafana/ui

Version:
86 lines (83 loc) 2.87 kB
import { jsx, jsxs } from 'react/jsx-runtime'; import { PureComponent, memo } from 'react'; import { faro } from '@grafana/faro-web-sdk'; import { t } from '@grafana/i18n'; import { Alert } from '../Alert/Alert.mjs'; import { ErrorWithStack } from './ErrorWithStack.mjs'; "use strict"; class ErrorBoundary extends PureComponent { constructor() { super(...arguments); this.state = { error: null, errorInfo: null }; } componentDidCatch(error, errorInfo) { var _a, _b, _c; if (this.props.errorLogger) { this.props.errorLogger(error); } else { (_c = (_a = faro) == null ? void 0 : _a.api) == null ? void 0 : _c.pushError(error, { context: { type: "boundary", source: (_b = this.props.boundaryName) != null ? _b : "unknown" } }); } this.setState({ error, errorInfo }); if (this.props.onError) { this.props.onError(error); } } componentDidUpdate(prevProps) { const { dependencies, onRecover } = this.props; if (this.state.error) { if (dependencies && prevProps.dependencies) { for (let i = 0; i < dependencies.length; i++) { if (dependencies[i] !== prevProps.dependencies[i]) { this.setState({ error: null, errorInfo: null }); if (onRecover) { onRecover(); } break; } } } } } render() { const { children } = this.props; const { error, errorInfo } = this.state; return children({ error, errorInfo }); } } const ErrorBoundaryAlert = memo( ({ title, children, style = "alertbox", dependencies, errorLogger, boundaryName }) => { const alertTitle = title != null ? title : t("grafana-ui.error-boundary.title", "An unexpected error happened"); return /* @__PURE__ */ jsx(ErrorBoundary, { dependencies, errorLogger, boundaryName, children: ({ error, errorInfo }) => { if (!errorInfo) { return children; } if (style === "alertbox") { return /* @__PURE__ */ jsx(Alert, { title: alertTitle, children: /* @__PURE__ */ jsxs("details", { style: { whiteSpace: "pre-wrap" }, children: [ error && error.toString(), /* @__PURE__ */ jsx("br", {}), errorInfo.componentStack ] }) }); } return /* @__PURE__ */ jsx(ErrorWithStack, { title: alertTitle, error, errorInfo }); } }); } ); ErrorBoundaryAlert.displayName = "ErrorBoundaryAlert"; function withErrorBoundary(Component, errorBoundaryProps = {}) { const comp = (props) => /* @__PURE__ */ jsx(ErrorBoundaryAlert, { ...errorBoundaryProps, children: /* @__PURE__ */ jsx(Component, { ...props }) }); comp.displayName = "WithErrorBoundary"; return comp; } export { ErrorBoundary, ErrorBoundaryAlert, withErrorBoundary }; //# sourceMappingURL=ErrorBoundary.mjs.map