Thursday, April 5, 2018

React Recipe: Components Error Handling

This article is about the Errors Handling in React Components using TypeScript

Not handled error in any part of the UI could crash the whole application.
Error Boundaries only catch errors in the components below them in the tree.
As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree.
Catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI.
Use JS error reporting services, so that you can learn about unhandled exceptions as they happen in production, and fix them.

Error Handling Prior to React v16.0

I've used quite straightforward way to figure out what went wrong, or why I see <!-- react-empty: xxx --> instead of my component:

TypeScript
render() {
    try {
      return (
        <div className="my-component">
          <p>{props.message}</p>
        </div>
      );
    } catch (e) {
      // tslint:disable-next-line
      console.error('My Component Error', e);
      return null;
    }
  }

Note: If you're facing with TypeError when used try / catch statement in render just return null.


Error Handling Since React v16.0:

As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree.
TypeScript
//...
componentDidCatch(error: Error, info: ErrorInfo) {
  // display fallback UI
  this.setState(() => { return { error: error }; });

  console.error('Caught an error: ', error);
}

render() {
  if (this.state.error ) {
    return <h2>{'Caught an error! ' + this.state.error}</h2>;
  }

  return (
    <div className="my-component">
      <p>{props.message}</p>
    </div>
  );
}

Note: info is an object with componentStack key.

So in case of error instead of your component you will something like following message in UI:

HTML
Caught an error! Error: Testing Error Boundaries
Error boundaries DO NOT catch errors inside event handlers.

Error Boundary as a Component:

We could write ErrorBoundary component once and use it wherever we need ^_^

TypeScript
export class ErrorBoundary extends Component<{children?: any}, {error: Error | null}> {

  state = { error: null }

  componentDidCatch(error: Error, info: ErrorInfo) {
    // display fallback UI
    this.setState(() => { return { error: error }; });
    // tslint:disable-next-line
    console.error('Caught an error: ', error);
  }

  render() {
    if (this.state.error) {
      return <h2>{'Caught an error! ' + this.state.error}</h2>;
    }

    return this.props.children;
  }
}

So now we could use it in my component render as well as in other components:

TypeScript
//...
render() {
  return (
    <ErrorBoundary>
      <div className="my-component">
        <p>{props.message}</p>
      </div>
    </ErrorBoundary>
  );
}

Conclusion

React Error Boundaries is a step forward into more controlled way to build a solid applications. It allows not only to allocate the problem fast, but to degrade gracefully as well.


see Also


9 comments:

  1. I really appreciate the work you have done, you explained everything in such an amazing and simple way.Good post. I was searched for this topic.
    https://www.bharattaxi.com

    ReplyDelete
  2. Thank you for sharing this informative post on React js. I was looking for this kind of information. It is very helpful.
    Best Web Development Services in Delhi

    ReplyDelete
  3. Really impressed with the article you provided. It was quite informative, effective, and easy to use. Chat apps have certainly grown to the top today and we, as Suffescom Solutions, are also working in the same niche. Be it clubhouse clone or any other cloning platform, we are the best entertainment app, clone providers. We use first-level interference to provide the best React Slack Clone chat App.

    ReplyDelete
  4. I really appreciate the work you have done, you explained everything in such an amazing and simple way.Good post.

    Mobile app development

    ReplyDelete
  5. Great Post. Very informative. Keep Sharing!!

    Apply Now for MERN Training Classes in Noida

    For more details about the course fee, duration, classes, certification, and placement call our expert at 70-70-90-50-90

    ReplyDelete
  6. Today, businesses are always looking for new ways to connect with customers and stay ahead of the competition. One effective method is using hybrid app development cost, which combines the best features of native and web apps. In 2024, it's crucial for businesses to understand the fundamentals of hybrid app development costs in order to make informed decisions.

    ReplyDelete