Blog |

Error Handling in React Native

Error Handling in React Native
Table of Contents

React Native has recently gained popularity among the mobile app developer community due to its cross platform compatibility, quick development cycle and better user experience. It is easier to develop, build and maintain apps using React Native.

For mobile apps, business success or failure is determined by user experience and retention rate. The retention rate can drop immediately if the application does not work properly, causing customers to switch to other apps or leave poor reviews in the app store. A fast response to critical errors is essential to minimize customer impact.

Let’s start by covering how to handle errors in vanilla React Native. We will then show you how Rollbar is a game changer to get better error monitoring.

Rollbar loves React Native

How to handle errors in React Native

Error handling in vanilla JavaScript can be achieved using try, catch and finally statements. You can use these statements to handle caught exceptions in React Native components.

try {
  var test;
  test.color;
} catch(err) {
  // handle error here
}

React Native has its own mechanism to handle uncaught exceptions. This allows you to track the error, display a message to the user, or attempt to recover. See the example below:

const previousHandler = ErrorUtils.getGlobalHandler();
ErrorUtils.setGlobalHandler((error, isFatal) => {
// handle the error here
  console.log(error);
});

Logging to the console works fine during development, but there is no out-of-the-box way to track these errors centrally after they are installed. This is essential to see how many of your users are affected by React Native errors, so that you can handle and prioritize fixes to critical ones.

Monitoring errors with Rollbar

Rollbar offers a real-time feed and instant alerts to make you aware of errors as they appear. It automatically tracks uncaught errors and crashes in your apps, as well as any items you report using the SDK. Even uncaught exceptions can quickly be tracked without the need for user-generated feedback. Rollbar provides detailed statistics, charts, and historical graphs about the errors within your software. Learn more about Rollbar’s features and how it can help you solve problems faster.

Next, we’ll show you to set up React Native to send errors to Rollbar and how to use it. The example below shows an application that triggers an exception when the user clicks on a button. The error message can be seen in Rollbar, including a stack trace which provides information about the line of code that caused the error.

Screenshot of Rollbar React Native Example

How to set up a React Native error handling project on Rollbar

Here are some simple steps describing how to set up your project on Rollbar. You can find more details in the React Native documentation. You can also follow along using our open source example application on GitHub.

  1. Visit https://rollbar.com and sign up for an account if you haven’t done so yet. Next, create your project and select Other from the list of notifiers. Select the client side access token that is generated for you. You’ll need this to configure Rollbar in the steps below.

  2. Open the command prompt in your project directory and type the following command to install the Rollbar React Native SDK.

$ npm install rollbar-react-native --save

Or

$ yarn add rollbar-react-native
  1. Link the React Native modules with the underlying project.
$ react-native link rollbar-react-native

Open the project entry point js file (in our case it’s index.js) and add the following code snippet.

import { Client } from 'rollbar-react-native';
const rollbar = new Client('MY_ACCESS_TOKEN');

Enable a source map in the Rollbar configuration

A source map will help you when handling and debugging a React Native error because it will show you the exact line in your code where errors occur. Mapping production React Native JavaScript code to your source files is slightly more complicated than in traditional JavaScript environments. This is due to the fact that iOS and Android generate different JavaScript bundles. Therefore, they have different stack traces, which need separate source maps.

You can specify which source map to use using the code_version parameter. Please note that code_version must be nested under the client and JavaScript keys to work.

import { AppRegistry } from 'react-native';
import App from './App';
import { Client } from 'rollbar-react-native'
const rollbar = new Client(new Configuration('MY-ACCESS-TOKEN', {
  payload: {
    client: {
      javascript: {
        source_map_enabled: true,
        code_version: '1234566.android',
        environment: 'production'
      }
    }
}
}));
AppRegistry.registerComponent('RollbarExample', () => App);

Generate Sourcemap

Next, you need to generate a source map of your source code bundle to find the actual place where an error occurred. Generating a source map for error handling in React Native is slightly different for each platform.

Android:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/index.android.bundle --assets-dest android/app/src/main/res/ --sourcemap-output sourcemap.android.js --sourcemap-sources-root ./

IOS:

react-native bundle --platform ios --entry-file index.ios.js --dev false --bundle-output
ios/main.jsbundle --assets-dest ios --sourcemap-output sourcemap.ios.js --sourcemap-sources-root ./

Upload the source map to Rollbar

Finally, you should upload the source map to the Rollbar. Be sure to specify the code version when you upload the source map to see full stacktraces for handling React Native errors. For example, via curl:

curl https://api.rollbar.com/api/1/sourcemap \
-F access_token=b2dea1fe24b44c5f86bbadf7a0d33782 \  -F version=1234566.android \           
-F minified_url=http://reactnativehost/index.android.bundle \
-F [email protected] \
-F [email protected] \
-F [email protected]

Source maps use file names for mapping minified symbols to the symbols contained in your original source code. Due to the nature of the JavaScript environment when using React Native, these file names include a prefix. Rollbar automatically rewrites these file names to be http://reactnativehost/<regular file path>. This allows you to set the minified_url with the fake protocol and host of http://reactnativehost to specify your minified JavaScript code.

Test Rollbar with an example React Native app

To test that it’s working, let’s create a page that will generate an error message. In the example below, you can generate an error by clicking the "Generate an error" button.

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Button, Alert
} from 'react-native';

export default class App extends Component<{}> {
  constructor(props) {
    super(props);
    this.state = {};
  }

  generateError = () => {
    var test;
    test.color; //This will generate a TypeError: undefined
  }

  render() {
    return (
      <View style={styles.container} >
        <Text style={styles.welcome}>
          Rollbar Example
        </Text>
        <View style={styles.loginButton} >
          <Button onPress={this.generateError} title='Generate an Error' />
        </View>
      </View>
    );
  }
}

When you click the "Generate an error" button it will generate an error message. It calls generateError which is creates a “TypeError: undefined is not an object (evaluating '(void 0).color')” error.

Viewing and handling errors in Rollbar

Next, open Rollbar to see what these errors look like in your account’s item page.The error we just generated should be called "TypeError: undefined is not an object (evaluating '(void 0).color')."

Screenshot of Rollbar React Native Error

Get more details by clicking on the item near the top of the list that says "TypeError: undefined is not an object (evaluating '(void 0).color')."

Screenshot of Rollbar React Native Error Details

You can now see the full traceback including the code file, line number and function name where the error occurred.

Conclusion

Error monitoring is one of the most important tools for identifying and handling React Native errors. Rollbar provides developers with information about what happened before, during and after an error was generated.

Rollbar’s React Native SDK makes it easy to add error tracking to your app. It captures detailed tracebacks when errors occur and only takes a few minutes to set up. You’ll know about errors right away so that your users can experience your app the way it is meant to be.

If you haven’t already, sign up for a 14-day free trial of Rollbar and let us help you take control of React Native errors.

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape