Discussion on handling of ExpressJS uncaughtException

  node.js, question

Some articles said, do not conduct uncaughtException monitoring in process inside, because it will cause the process to hang, but how to deal with it remains to be studied. I came up with a way to add a midleware to save the response and then return it to the user in the uncaughtException inside. Single machine is feasible. Although there may be some problems, it is better than nothing. Let’s look at it and see if there is a better way.

app.use(function (req, res, next) {
 process.responseObject = res;
 next();
 });
 
 process.on('uncaughtException', function (err) {
 Error ('caughtexception:' plus err.stack);
 var res = process.responseObject;
 
 if(!  res) return;
 
 if (app.get('env') === 'development') {
 res.status(err.status || 500);
 res.render('error', {
 message: err.message,
 error: err
 });
 }else{
 
 res.status(err.status || 500);
 res.render('error', {
 message: err.message,
 error: {}
 });
 bracket
 
 });

The advantage of this method is that the process will not be held up, and the disadvantage is that the response object is global. If multiple users have problems at the same time, chaos will be caused.

In addition, there is another processing method to make it hang up. Here, some data before hanging up are stored. Of course, pm2 must be combined to restart it.

Please do not use this mode, use cluster or pm2 cluster model for multi-thread processing, and restart after hanging up.