UNPKG

@grafana/faro-react

Version:

Faro package that enables easier integration in projects built with React.

64 lines 2.72 kB
import { Component, isValidElement } from 'react'; import { isFunction } from '@grafana/faro-web-sdk'; import { api, internalLogger } from '../dependencies'; import { isReactVersionAtLeast17 } from '../utils'; import { faroErrorBoundaryInitialState } from './const'; export class FaroErrorBoundary extends Component { constructor(props) { super(props); this.state = faroErrorBoundaryInitialState; this.resetErrorBoundary = this.resetErrorBoundary.bind(this); } getErrorWithComponentStack(error, errorInfo) { if (!isReactVersionAtLeast17 || !errorInfo.componentStack) { return error; } const newError = new Error(error.message); newError.name = `React ErrorBoundary ${error.name}`; newError.stack = errorInfo.componentStack; return newError; } static getDerivedStateFromError(error) { return { hasError: true, error, }; } componentDidCatch(error, errorInfo) { var _a, _b, _c, _d; const errorWithComponentStack = this.getErrorWithComponentStack(error, errorInfo); (_b = (_a = this.props).beforeCapture) === null || _b === void 0 ? void 0 : _b.call(_a, errorWithComponentStack); api.pushError(errorWithComponentStack, this.props.pushErrorOptions); (_d = (_c = this.props).onError) === null || _d === void 0 ? void 0 : _d.call(_c, errorWithComponentStack); this.setState({ hasError: true, error }); } componentDidMount() { var _a, _b; (_b = (_a = this.props).onMount) === null || _b === void 0 ? void 0 : _b.call(_a); } componentWillUnmount() { var _a, _b; (_b = (_a = this.props).onUnmount) === null || _b === void 0 ? void 0 : _b.call(_a, this.state.error); } resetErrorBoundary() { var _a, _b; (_b = (_a = this.props).onReset) === null || _b === void 0 ? void 0 : _b.call(_a, this.state.error); this.setState(faroErrorBoundaryInitialState); } render() { if (!this.state.hasError) { return isFunction(this.props.children) ? this.props.children() : this.props.children; } const element = !isFunction(this.props.fallback) ? this.props.fallback : this.props.fallback(this.state.error, this.resetErrorBoundary); if (isValidElement(element)) { return element; } if (this.props.fallback) { internalLogger === null || internalLogger === void 0 ? void 0 : internalLogger.warn('ErrorBoundary\n', 'Cannot get a valid ReactElement from "fallback"'); } return null; } } //# sourceMappingURL=FaroErrorBoundary.js.map