Installation

The official Raygun provider for Node.js allows you to easily access crash reporting and error monitoring for your node.js network application.

This provider is flexible and supports many configuration scenarios - you can have it running and sending errors quickly, by manually placing send() calls when you detect an error. If you are using the Express.js web application framework, you can add the included middleware at the end of your middleware definitions. Or, you can use node.js domains.

The provider can send Error objects, with error details (time, message etc) a stack trace, request data, environment data, custom user data and more. If you wish to manually send other information, the transport object has a Send function which will pass data to Raygun with the required fields.


Install the raygun library with NPM:

npm install raygun

Or with Yarn:

yarn add raygun

Create an instance of RaygunClient using your app API key. Your app API key is displayed when you create a new application in your Raygun account, or can be viewed in the application settings.

const raygun = require('raygun');
const raygunClient = new raygun.Client().init({
  apiKey: 'paste_your_api_key_here',
  batch: true,
  reportUncaughtExceptions: true
});

When the reportUncaughtExceptions option is enabled, uncaught exceptions will automatically be captured and sent to Raygun.


Deploy Raygun into your production environment for best results, or raise a test exception. Once we detect your first error event, the Raygun app will automatically update.


The above instructions will setup Raygun to automatically detect and send all unhandled exceptions. Sometimes you may want to send exceptions manually, such as handled exceptions from within a try/catch block.

You can report errors manually by calling raygunClient.send(error). For example:

try {
  // some code that may throw an error
} catch (error) {
  raygunClient.send(error);
}

A similar example for Node style callbacks:

function handleResult(error, result) {
  if (error) {
    raygunClient.send(error);
    return;
  }

  // process result
}

If you're working directly with promises, you can pass raygunClient.send directly to .catch.

const axios = require('axios');

axios
  .get('example.com')
  .then(handleResponse)
  .catch(raygunClient.send);

If you are using Express.js to develop a web application, you can use the provided middleware as an error handler, at the bottom of your middleware definitions:

const raygunClient = new raygun.Client().init({apiKey: '{{paste_your_api_key_here}}'});

// ...
app.use(express.static(path.join(__dirname, 'public')));
app.use(raygunClient.expressHandler);

The Express documentation says, though not strictly required, by convention you define error-handling middleware last, after other app.use() calls, but that is incorrect. If the app.use(raygunClient.expressHandler); call is not immediately before the app.listen call, then errors will not be handled by Raygun.

Note that the Express middleware handler will pick up and transmit any err objects that reach it. If the app code itself chooses to handle states that result in 4xx/5xx status codes, these will not result in an error payload sent to Raygun.


You can pass custom data in on the Send() function, as the second parameter. For instance:

client.send(new Error(), { 'mykey': 'beta' }, function (response){ });

If you're using the raygunClient.expressHandler, you can send custom data along by setting raygunClient.expressCustomData to a function. The function will get two parameters, the error being thrown, and the request object.

const raygunClient = new raygun.Client().init({apiKey: "yourkey"});

raygunClient.expressCustomData = function (err, req) {
  return { 'level': err.level };
};

client.send(new Error(), {}, function (response) { });

The value passed to the 3rd argument callback is the response from the Raygun API - there's nothing in the body, it's just a status code response. If everything went ok, you'll get a 202 response code. Otherwise we throw 401 for incorrect API keys, 403 if you're over your plan limits, or anything in the 500+ range for internal errors. We use the nodejs http/https library to make the POST to Raygun, you can see more documentation about that callback here.


You can send the request data in the Send() function, as the fourth parameter. For example:

client.send(new Error(), {}, function () {}, request);

If you want to filter any of the request data then you can pass in an array of keys to filter when you init the client. For example:

const raygun = require('raygun');
const raygunClient = new raygun.Client().init({
  apiKey: 'paste_your_api_key_here',
  filters: ['password', 'creditcard']
});

You can add tags to your error in the Send() function, as the fifth parameter. For example:

client.send(new Error(), {}, function () {}, {}, ['Custom Tag 1', 'Important Error']);

Tags can also be set globally using setTags

client.setTags(['Tag1', 'Tag2']);

You can set raygunClient.user to a function that returns the user name or email address of the currently logged in user.

An example, using the Passport.js middleware:

const raygunClient = new raygun.Client().init({
  apiKey: "{{paste_your_api_key_here}}"
});

raygunClient.user = function (req) {
  if (req.user) {
    return {
      identifier: req.user.username,
      email: req.user.email,
      fullName: req.user.fullName,
      firstName: req.user.firstName,
      uuid: req.user.deviceID
    };
  }
}

The string properties on a User have a maximum length of 255 characters. Users who have fields that exceed this amount will not be processed.


Call setVersion(string) on a RaygunClient to set the version of the calling application. This is expected to be of the format x.x.x.x, where x is a positive integer. The version will be visible in the dashboard.


Call Raygun.onBeforeSend(), passing in a function which takes up to 5 parameters (see the example below). This callback function will be called immediately before the payload is sent. The first parameter it gets will be the payload that is about to be sent. Thus from your function you can inspect the payload and decide whether or not to send it.

You can also pass this in as an option to init() like so:

raygunClient.init({ onBeforeSend: function(payload) { return payload; } });

From the supplied function, you should return either the payload (intact or mutated as per your needs), or false.

If your function returns a truthy object, Raygun4Node will attempt to send it as supplied. Thus, you can mutate it as per your needs - preferably only the values if you wish to filter out data that is not taken care of by the filters. You can also of course return it as supplied.

If, after inspecting the payload, you wish to discard it and abort the send to Raygun, simply return false.

Example:

const myBeforeSend = function (payload, exception, customData, request, tags) {
  console.log(payload); // Modify the payload here if necessary
  return payload; // Return false here to abort the send
}

Raygun.onBeforeSend(myBeforeSend);

You can enable a batched transport mode for the Raygun client by passing {batch: true} when initializing.

const raygunClient = new raygun.Client().init({
  apiKey: 'paste_your_api_key_here',
  batch: true,
  batchFrequency: 5000 // defaults to 1000ms (every second)
});

The batch transport mode will collect errors in a queue and process them asynchronously. Rather than sending each error one at a time as they occur, errors will be batched and sent at regular intervals.

If your application generates and reports large volumes of errors, especially in a short duration, the batch transport mode will perform better and operate with less network overhead.

You can control how often batches are processed and sent by providing a batchFrequency option, which is a number in milliseconds.


Raygun can cache errors thrown by your Node application when it's running in 'offline' mode. By default the offline cache is disabled. Raygun4Node doesn't detect network state change, that is up to the application using the library.

Raygun includes an on-disk cache provider out of the box, which required write permissions to the folder you wish to use. You cal also pass in your own cache storage.

When creating your Raygun client you need to pass through a cache path

const raygunClient = new raygun.Client().init({
  apiKey: 'paste_your_api_key_here',
  isOffline: false,
  offlineStorageOptions: {
    cachePath: 'raygunCache/',
    cacheLimit: 1000 // defaults to 100 errors if you don't set this
  }
});

The Raygun client allows you to set it's online state when your application is running.

To mark as offline: raygunClient.offline();

To mark as online: raygunClient.online();

When marking as online any cached errors will be forwarded to Raygun.

You're able to provide your own cache provider if you can't access to the disk. When creating your Raygun client, pass in the storage provider on the offlineStorage property

Example:

const sqlStorageProvider = new SQLStorageProvider();

const raygunClient = new raygun.Client().init({
  apiKey: 'paste_your_api_key_here',
  isOffline: false,
  offlineStorage: sqlStorageProvider,
  offlineStorageOptions: {
    table: 'RaygunCache'
  }
});

Required methods

  • init(offlineStorageOptions) - Called when Raygun is marked as offline. offlineStorageOptions is an object with properties specific to each offline provider
  • save(transportItem, callback) - Called when marked as offline
  • retrieve(callback) - Returns an array of cached item filenames/ids
  • send(callback) - Sends the backlog of errors to Raygun

We recommend that you limit the number of errors that you are caching so that you don't swamp the clients internet connection sending errors.


You can provide your own grouping key if you wish. NOTE: We only recommend doing this if you are having issues with errors not being grouped properly.

When initializing Raygun, pass through a groupingKey function.

const raygunClient = new raygun.Client().init({
  apiKey: 'paste_your_api_key_here',
  groupingKey: function(message, exception, customData, request, tags) {
    return "BUILD_CUSTOM_KEY_HERE";
  }
});

By default Raygun4Node tries to convert unknown objects into a human readable string to help with grouping, this doesn't always make sense.

To disable it:

const raygunClient = new raygun.Client().init({
  apiKey: 'paste_your_api_key_here',
  useHumanStringForObject: false
});

If your custom error object inherits from Error as its parent prototype, this isn't necessary however and these will be sent correctly.


By default Raygun4Node doesn't include column numbers in the stack trace. To include column numbers add the option reportColumnNumbers set to true to the configuration.

const raygunClient = new raygun.Client().init({
  apiKey: 'paste_your_api_key_here',
  reportColumnNumbers: true
});

Including column numbers can enable source mapping if you have minified or transpiled code in your stack traces.


Raygun supports source mapping for Node.js stacktraces which include column numbers. To enable this feature you will need to upload your map files to the JavaScript Source Map Center and enable the processing of Node.js error stacktraces.

Raygun supports source mapping for Node.js stacktraces which include column numbers. To enable this feature simply upload your map files as per the instructions on this page and enable the processing of Node.js errors with this setting in Raygun.


Managing files in the JavaScript Source Map Center Files in the JavaScript Source Map Center can be managed via a few API calls.

A GET request to https://app.raygun.com/jssymbols/[applicationIdentifier] will return a JSON object listing all files within the center. eg.

curl -L
  -X GET
  -u my@email.com:mypassword
  https://app.raygun.com/jssymbols/[applicationIdentifier]

Returns:

{
  "Count": totalNumberOfItems,
  "Items": [
    {
       "Url": "https://urlOfItem",
       "FileName": "fileName.js",
       "UploadedOn": "2016-01-01..."
    },
    ...
  ]
}

A DELETE request to https://app.raygun.com/jssymbols/[applicationIdentifier]/all will remove all files within the center. eg.

curl -L
  -X DELETE
  -u my@email.com:mypassword
  https://app.raygun.com/jssymbols/[applicationIdentifier]/all

A DELETE request to https://app.raygun.com/jssymbols/[applicationIdentifier] will remove files with the specified URLS from the center. eg.

curl -L
  -X DELETE
  -u my@email.com:mypassword
  -F "url=https://example.com/js/myjs.min.map"
  https://app.raygun.com/jssymbols/[applicationIdentifier]

All requests use the same authentication methods as the upload call (Basic Authentication and Token Authentication).


If you're using asynchronous AWS Lambda functions, the .send() method must be wrapped in an awaited Promise, so the connection is not interrupted by the Lambda finishing. The below code snippet creates a function that returns a Promise which is resolved when the Raygun exception has been dispatched.

...
return {
  catchPromise: (reason) => {
    console.log('Caught promise rejection');
    var err = new Error( `Possibly Unhandled Rejection.\n\nReason ${reason}`);
    const p = new Promise(function (resolve, reject) {
      console.log(raygunClient.send(err, {}, function () {
        console.log('Sent promise rejection');
        resolve();
      }));
    });

  return p;
};
...

At this point we can now use the catchPromise() method as the last .catch() of our Promise chain:

...
  return storePhoto(photo, stage);
}).then(() => {
  return {
    success: true,
    photo photo
  };
}). catch(errorHandlers.catchPromise);
...

If you need additional details, this article on Error logging with Raygun ️and AWS Lambda may be useful.

The provider is open source and available at the Raygun4node repository.