ExpressJS Error Handling with Raygun

| 2 min. (334 words)

ExpressJS error handling is easy when you use Raygun! Using the raygun npm package you can be zapping errors in minutes.

To begin, you need to install the npm module using npm install --save raygun. Once npm has finished doing its thing, we need to hook Raygun into our Express app.

In your main Express app file (probably called app.js), add the following:

var raygun = require('raygun');
var raygunClient = new raygun.Client().init({ apiKey: 'your API key' });

Make sure you remember to put your own API key in the init call!

Now comes the tricky part: to get Raygun to work in Express 4, you need to put the app.use() call just before the app.listen() call. Otherwise, it won’t work.

app.use(raygunClient.expressHandler);

That’s it, we’re done! Well, if you just want the basics, then you’re done. Otherwise, read on for more tips.

One of Raygun’s handy features is User Tracking – if you tell us who was using your app when it crashed, then we can do all sorts of useful things like tell you how many crashes that user has experienced, how to get in touch with them over social media, and which errors are affecting the most users.

To enable this magical feature, add the something like this to your raygunClient setup code:

raygunClient.user = function (req) {
  if (req.user) {
    return {
      identifier: req.user.id,
      email: req.user.email,
      fullName: req.user.fullname
    };
  }
}

Your user data will probably look different to this example, but hopefully you get the idea! The documentation is here if you need it: https://github.com/MindscapeHQ/raygun4node#raygunclientuserreq

Another thing you should probably do is set your app’s version on the raygunClient. That’s easy too:

raygunClient.setVersion('1.0.0.0');

With this you can mark errors as Resolved in a particular version, or search for errors that occurred in one version of your app.

Grab your Raygun trial

Want awesome error handling for ExpressJS? Dive in and hook up Raygun in your apps now! If you need a Raygun account, as always there’s the 14 day trial here.