Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Error Monitoring in React Native

DZone's Guide to

Error Monitoring in React Native

In this post, we go over how to use error monitoring in your mobile application code using React Native and a few other handy tools. Read on to get started!

· Web Dev Zone ·
Free Resource

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

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.

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 errors and to 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 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 debugging 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. Generating a source map 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. 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 source_map=@sourcemap.android.js \
-F index.js=@index.js \
-F App.js=@App.js

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 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')."

Image title

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')."

Image title

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 fixing 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.

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:
data errors ,error reporting ,web dev ,react native ,error handling

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}