Search code examples
node.jsexpresserror-handlingraygunraygun.io

How do I shut down my process after using Raygun's express-handler?


I'm building an app with NodeJS and Express and have recently incorporated error handling with Raygun.

Raygun provides an error handler specifically for use with Express, but it must be the last piece of middleware to run. Right now I have:

//Log the domain id, req, and error to the console
app.use(function errorHandler(err, req, res, next) {
  console.log('error on request %d %s %s: %s', process.domain.id, req.method, req.url, err)
  next(err)
})
//Log the error to Raygun
//!Must be last piece of middleware to be defined
app.use(raygunClient.expressHandler);

But the problem is that the server continues to run, potentially leaving the app in an unknown state. I'd like to do a graceful server shutdown, but if I add

//Shuts down the process
app.use(function errorHandler(err, req, res, next) {
  process.exit()
})

then Raygun's express-handler doesn't work.

What do?


Solution

  • You can define custom raygunClient.expressHandler, much like the one defined in the library.

    app.use(function errorHandler(err, req, res, next) {
      console.log('error on request %d %s %s: %s', process.domain.id, req.method, req.url, err)
      next(err)
    }) 
    
    app.use(function (err, req, res, next) {
      raygunClient.send(err, {}, function (response) {
        //all done
        process.exit(1);
      }, req);
      next(err);
    });
    

    Now you also have the ability to send customData as 2nd argument and tags as 5th argument which was not possible with the defaul error handler.