Catch all uncaughtException for Node js app

做~自己de王妃 提交于 2019-11-27 02:35:03

问题


I have a question: how do I can handle all uncaught Exception (operations/developer error will take all service down) for my node app. Then I can send an email alert to me whenever catch an error.


回答1:


You can use process 'uncaughtException' and 'unhandledRejection' events.

Also remember that it is not safe to resume normal operation after 'uncaughtException', because the system becomes corrupted:

The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process.

Example:

process
  .on('unhandledRejection', (reason, p) => {
    console.error(reason, 'Unhandled Rejection at Promise', p);
  })
  .on('uncaughtException', err => {
    console.error(err, 'Uncaught Exception thrown');
    process.exit(1);
  });



回答2:


You could use the Domain API : https://nodejs.org/api/domain.html But it is deprecated and not recommended anyway.

In general, you want to handle errors anywhere they may occur and avoid a "catch all" approach.

If an error occurs, ignoring it is no incentive to fix it, and in some cases could lead to you not even knowing that your program is malfunctioning.

Instead, the best way to handle it is to have your program crash, log the crash (and the stack/core dump), then restart it automatically, using pm2 or nodemon.

For a (very) long but insightful speech by Joyent (Node creators), I strongly recommend you read this link : Error handling in Node.JS

There's also a process.on('uncaughtException') event (that you should also not use)

Edit: A bit more details and an attempt at solving your issue. Using a software like pm2 to restart your app on crash, you will also be able to see the error.log, which will give you the stack trace. So it seems that the only thing you still need is to be alerted of the crash.

For that, you may want to have a look at interfaces like keymetrics (same guys who made pm2) which potentially could alert you on errors.

A cool solution I used once, a long long time ago was as follows :

  • when your app (re)starts, it looks for an error log
  • If it finds one, it alerts you with the content of the log file
  • it then renames/move the error logfile to a different location

I wouldn't necessary recommend this solution, but it fits all the specs you need, so have fun with it!

Edit2 : If you feel like delving deeper into the topics of service development and best practices, have a look at his link suggested by @Paul in the comments : https://12factor.net/




回答3:


the best way is to let the application crash, log the error and then restart the process. you can do it simply like this

var cluster = require('cluster');

var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  for (var i = 0; i < numCPUs; ++i) {
    cluster.fork();
  }
  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
    cluster.fork();
  });
} else {
  var http = require('http');
  var httpServer = http.createServer(app).listen(httpPort, function () {
      console.log('process id local', process.pid)
      console.log("http server started at port " + httpPort);
  });
}

process.on('uncaughtException', function (err) {
  console.error((new Date).toUTCString() + ' uncaughtException:', err.message)
  console.error(err.stack)
  process.exit(1)
})

`



来源:https://stackoverflow.com/questions/40867345/catch-all-uncaughtexception-for-node-js-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!