8

I'm using pm2 (https://github.com/Unitech/pm2) in my node.js project. Also I'm sending logs of errors of the app in Logentries (https://logentries.com).

I wonder is it possible to log uncaught exceptions from the app (when something fails badly and pm2 restarts the app for example)? I know that using process.on('uncaughtException') is bad practice so would like to hear some suggestions.

Thanks!

Kosmetika
  • 20,774
  • 37
  • 108
  • 172

1 Answers1

7

Where did you read that process.on('uncaughtException') is a bad practice?

As long as you exit the process after logging the exception I don't see what's bad, here is an example:

process.on('uncaughtException', function(e) {
    console.error('Ouch, an unhandled exception');
    //I like using new Error() for my errors (1)
    console.error(e instanceof Error ? e.message : e);
    process.exit(1);
});

(1): Javascript Error reference

Edit pm2-interface is now deprecated, use require('pm2') instead. You will be able to do exactly the same as below by using bus system events.


An alternative with pm2 is to use pm2-interface and listening to the process:exit or process:exception events:

var ipm2 = require('pm2-interface')();

ipm2.on('ready', function() {
  console.log('Connected to pm2');

  ipm2.bus.on('process:exception', function(data){
    console.log(data.pm2_env.name + 'had an exception');
  });
});

This is really usefull when managing more than one process through a monitoring process.

You might want to check the blog post on how to build a custom pm2 logger. It can give you some ideas about monitoring processes through pm2-interface.

soyuka
  • 8,839
  • 3
  • 39
  • 54
  • 1
    From the npm docs: `'uncaughtException' is a crude mechanism for exception handling intended to be used only as a last resort` https://nodejs.org/api/process.html#process_warning_using_uncaughtexception_correctly – cloakedninjas Oct 16 '19 at 12:45
  • 1
    It is not a good practice for production process to catch and resolve exceptions. However if you want to catch errors while remotely monitoring/debugging, it is useful – nvbalaji Nov 17 '19 at 13:51
  • Your link "bus system events" is broken – Benjamin Crouzier Apr 15 '20 at 17:02