Search code examples
javascriptnode.jspm2

Is there a way to divert logs/errors to run code in pm2?


I want to be able to run code to log the error correctly then crash the process instead of immediately crashing the process if there is an error, like a global try catch. Is there a way to do that? I want a solution like

process.on("uncaughtException", err => {
    logTheErrorSomehow();
    process.exit(1);
});

but that doesn't work in pm2, only node.


Solution

  • After a week of trial and error, I came across this solution that worked:

    const pm2 = require('pm2');
    
    pm2.launchBus(function(err, pm2_bus) {
      pm2_bus.on('process:exception', function(packet) {
        await logTheErrorSomehow(packet);
        process.exit(1);
      });
    });
    

    This works just like process.on("uncaughtException") did with node.