Home > Article > Web Front-end > How to use Raygun to handle errors in Node.js applications_node.js
Our raygun4node package provides a convenient way to send your Node.js errors to Raygun. It can be easily installed using npm:
npm install raygun
It gives you a raygun client that you can use to configure your API key and can be used to send error messages manually. But later you might say, “I don’t want to send all the errors manually Send them all to Raygun, that sounds like a lot of work to do!" If you are using express.js, then using express's processor can easily solve this worry.
var raygun = require('raygun'); var raygunClient = new raygun.Client().init({ apiKey: 'your API key' }); app.use(raygunClient.expressHandler);
In other cases you may just want to listen for uncaughtException and send an error message this 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 start doing this, you have to understand what it means. But when a time bubble goes all the way back into the event loop, this event will be emitted. If you add a listener for this event, then The default action will no longer occur. The default action is to print out the call stack information and exit the process. If you continue after triggering this, your node process will be in an undefined state. node.js The documentation specifically says that you should not use this, and that it may be removed in the future. The suggested alternative is to use domains. A small and simple example is shown below, and you can see the raygun client How it adapts to your use of the domain.
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);
Hope this will give you a better understanding of error handling in Node.js using Raygun.
Continuously clean up errors!