Search code examples
node.jsexpresserror-handlinguncaught-exceptionpm2

pm2 does not restart worker when express error occur


I'm using pm2 to manage process in my nodejs express application (running in cluster mode).

We had 2 kind of error handler

  • FIRST: 'uncaughtException' will be handled with

    process.on('uncaughtException', function(err){});
    

Actually, I do not declare an handler like this cause of letting pm2 detect died worker in this case so restart the died worker automatically.

  • SECOND: express error handler, I mean the error will be forwarded to express error handler, not uncaughtException handler, the error handler like below

    app.use(function(err, req, res, next) {})
    

I also do not declare this error handler for same purpose as uncaughtException. But pm2 does not restart node in this case.

Any idea about this problem? Many thanks


Solution

  • When catching errors with express error handler or even "uncaughtException" event, the process is still running, so pm2 won`t restart it. If you want pm2 to restart after each exception, I would suggest something like this:

        process.on('uncaughtException', function(e) {
          console.log('An error has occured. error is: %s and stack trace is: %s', e, e.stack);
          console.log("Process will restart now.");
          process.exit(1);
        })
    

    Same goes for the express error handler. When we execute process.exit method, the process will terminate and pm2 will restart it.