Hackernoon logoReact JS and React Native Handle Exceptions Gracefully by@mirthfulnahid

React JS and React Native Handle Exceptions Gracefully

image
Mirthful Nahid Hacker Noon profile picture

@mirthfulnahidMirthful Nahid

Handling exception in ReactJs/ React Native is thing ,which beginners often forget to handle. I was also the same . In production , this can bring chaos.

In React prod , page will go blank, causing bad UX.

In React Native, Your app will crash unexpectedly .

React has a beautiful solution to this problem.the ComponentDidCatch() method. This method will catch any error 😤 in its own component and also the child components.

the trick is to use this method in a seperate component. Catch all the errors, in componentDidCatch() method. This method got two parameters.

First is error, second is errorInfo.

From the errorInfo object, you can track from which component, the error is coming from.

You can use this technique for react and react native. You can show beautiful error page to visitors.

by __Dev__, you can check the development mode is on or not. Then show the error accordingly.

You can send this error to server end , if there is any crash log there.

At last, you need to wrap you main Root Component with that errorComponent.

Thanks … have a nice day…

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.