Search code examples
javascriptnode.jspm2

PM2 is catching errors before they reach 'uncaught Exception' in Node.js


Hey Guys, I am running a discordbot with Discord.js in Node.js. My goal is to run it via pm2 on a Linux Ubuntu Server.

I want to build a cleanup process before exiting the program on uncaught Exception.

However when I throw a sample error and run it via pm2 uncaught Exception is not reached, pm2 is just logging the error and continue running the script. When running it directly with Node.js, without pm2 everything works as expected.

Here is my code:

process.on('uncaughtException', async (err, origin) => {
    console.log('test')
    // await Cleanup();
    process.exit(1);
});

Here the console output running it with pm2:

Error: Test error
at Object.execute (script xxxx)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async xxx

As you can see pm2 is kind of preventing the Test error to reach uncaughtException. Pm2 is not restarting the script, and is not logging 'test'

I also tried catching the error via SIGINT or SIGTERM but none of these are working.

Is there an option in pm2 to disable this behavior?

Thanks for any help!


Solution

  • The function in which the error is thrown is async. That led me to the docs of the unhandledRejection event.

    In addition to uncaughtException I added unhandledRejection:

    process.on('uncaughtException', async (err, origin) => {
      await Cleanup(...); //my own cleanup
      process.exit(0);
    });
    
    process.on('unhandledRejection', async (reason, promise) => {
      await Cleanup(...); //my own cleanup
      process.exit(0);
    });
    

    Now pm2 is restarting after a cleanup whenever an uncaught Error/Exception is thrown.