2

I'm using React 16.3 which has support for error boundaries, via ComponentDidCatch() function overrides. I'm using typescript as well.

For ease of future debugging I want to somehow catch any errors/exceptions at the component level in order to highlight (draw yellow square) in the UI indicating the possition of broken component.

How could I do this without having to explicitly declare error boundary around every single component that I use?

Perhaps its possible to wrap them during build time? I also presume error boundary would need to somehow get the props from broken component in order to know where to draw yellow square. How could I accomplish that?

I'm quite new to React so thanks in advance.

1
  • I also probably should note that I'm also using couple custom basic components (Text/View/Image) which do not inherit from React components. Commented May 7, 2018 at 20:47

1 Answer 1

2

I think if you want to use error boundary then use it inside the dom render.

import * as ReactDOM from 'react-dom';
import {ErrorBoundary} from 'your-path';

    ReactDOM.render(
        <ErrorBoundary>
           //Router or other stuff
        </ErrorBoundary>,
        document.getElementById('root') as HTMLElement
    );

create ErrorBoundary component like this.

import * as React from 'react';

interface IErrorBoundaryState {
    isError: boolean;
    error: React.ErrorInfo;
}

export class ErrorBoundary extends React.Component<{}, IErrorBoundaryState> {

    this.state = {isError: false, error: null};

    componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
        this.setState({ isError: true, error: errorInfo });
    }

    render(): any {
        if (this.state.isError) {
            return <div>{this.state.error.componentStack}</div>;
        }

        return this.props.children;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.