import * as Sentry from '@sentry/browser';
import React from 'react';
import ErrorPage from 'src/pages/error';

interface State {
    error?: Error;
}

interface Props {
    path?: string | string[];
}

export default class ErrorBoundary extends React.Component<Props, State> {

    constructor(props: Props) {
        super(props);
        this.state = {};
    }

    static getDerivedStateFromError(error: Error) {
        return { error };
    }

    componentDidCatch(error: Error, info: React.ErrorInfo) {
        const { componentStack } = info;
        this.setState({ error });
        Sentry.withScope((scope) => {
            scope.setExtras({ componentStack });
            Sentry.captureException(error);
        });
    }

    render() {
        const { error } = this.state;
        const { children } = this.props;

        if (error)
            return <ErrorPage error={error} />;

        return children;
    }
}
