Catch ‘React Native Errors’ If You Can!
One of the worst scenarios for a mobile application is crashing without handling the errors gracefully. if you don’t have any plan to handle the unexpected errors then you have the plan to fail!
Though error handling in a native application can be straightforward, it can be quite tricky in a React native app. There is two sides that could cause your app to crash, Native side & The JS side. In this article, we are going to talk about methods we used to handle exceptions in “Sanjagh”. Here are the four methods that can be quite useful in most of the use cases.
Sanjagh is an online marketplace for services who try to provide an optimized connection between customers and professionals.
There is a good explanation here:
The try…catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try-catch statement catches it.
To be more clear, if you have lines of code in a block of code (function, …) that may throw any exceptions, you can cover it in a try-catch like below:
Every promise should be followed by a catch to let you handle the exceptions that are thrown as below:
ComponentDidCatch became part of the React 16 lifecycles. It means that once an error happens in a child component the parent can catch & handle it gracefully. The good news is that by componentDidCatch you can have the beautiful Error Boundaries. But the bad news is that it just can catch the error which is happening in the react lifecycles(constructor, componentDidCatch, render,…). Here is an example. If the child component has a button and pressing the button throws an exception, that exception won’t be caught in its parent component. No need to mention that this includes the events like setTimeout & setInterval or any other events as well. The code below is an example of an error boundary:
So in the parent component we could do this:
It’s pretty obvious that you can render another component when you catch a buggy component, instead of making it invisible.
4) Global Error Handling
For other cases that the above methods doesn’t work properly, there is another way that we can use the global handler to catch the uncaught exceptions. It can be simply implemented as below:
These four methods should be enough for most use cases in the js part. As for the native part you either handle it yourself (if you have developed sth there) or you can use ‘react-native-exception-handler’ which can be useful for many cases.