Node.js Error Handling

| 2 min. (341 words)

We provide a convenient way to send your Node.js errors to Raygun with our package raygun4node. This is easy to install using npm

npm install raygun

This will provide you with a raygun client that you can configure with your API key and use to manually send errors. But wait a minute you might say, “I don’t want to be manually sending all my errors up to Raygun, that sounds like a lot of hard work!” If you are using express.js then this is easily solved with our express handler.

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

In other cases you might be thinking it’s just a case of listening to uncaughtException and sending errors through that way.

var raygun = require('raygun');
var raygunClient = new raygun.Client().init({ apiKey: 'your API key' });
process.on('uncaughtException', function(err) {
  raygunClient.send(err);
});

If you are going to do this then you need to understand the implications. This event is emitted when an exception bubbles all the way back to the event loop. If you add a listener for this event then the default action will no longer occur. The default action is to print the stack trace and exit the process. If you continue on after hitting this then your node process will be in an undefined state. The node.js documentation is very specific that you should not be using this and that it may be removed in the future. The alternative presented is to use domains. Presented below is a small trivial example so you can see how the Raygun client might fit into your use of domains.

var domain = require('domain');
var raygun = require('raygun');
var raygunClient = new raygun.Client().init({ apiKey: 'your API key' });
var server = require('http').createServer(function (req, res) {
  var d = domain.create();
  d.on('error', function (err) {
    raygunClient.send(err);
    // clean up and end
  });
  d.add(req);
  d.add(res);
  d.run(function () {
    // handle the req, res
  });
});
server.listen(3000);

Hopefully this helps you to better understand error handling in Node.js with Raygun.

Keep blasting errors!