如何防止node.js崩溃? try-catch不工作 [英] How do I prevent node.js from crashing? try-catch doesn't work

查看:639
本文介绍了如何防止node.js崩溃? try-catch不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我的经验,php服务器会抛出异常到日志或服务器端,但node.js只是崩溃。用try-catch包围我的代码不工作,因为一切都是异步完成的。我想知道其他人在他们的生产服务器上做什么。

From my experience, a php server would throw an exception to the log or to the server end, but node.js just simply crashes. Surrounding my code with a try-catch doesn't work either since everything is done asynchronously. I would like to know what does everyone else do in their production servers.

推荐答案

其他答案真的疯了,节点自己的文档,位于 http://nodejs.org/docs/latest/api/process .html#process_event_uncaughtexception

Other answers are really insane as you can read at Node's own documents at http://nodejs.org/docs/latest/api/process.html#process_event_uncaughtexception

如果有人使用其他陈述的答案,请阅读Node文档:

If someone is using other stated answers read Node Docs:


请注意, uncaughtException 是一个非常粗略的异常处理机制,可能会在将来删除

Note that uncaughtException is a very crude mechanism for exception handling and may be removed in the future

所以经过我终于想出了Node文档本身的建议:

So after going through I finally came up with what Node document itself suggests:


使用 domains 替换 cluster 。如果您确实使用 uncaughtException ,请在每个未处理的异常后重新启动应用程序!

Don't use it, use domains with cluster instead. If you do use uncaughtException, restart your application after every unhandled exception!

解决方案是群集

。 我们实际上是发送错误响应到触发错误的请求,同时让其他人在正常时间完成,并停止侦听该工作者的新请求。

What we actually do is send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker.

这样,域使用与集群模块紧密相连,因为当工作程序遇到错误时,主进程可以分叉新的工作线程。请参阅下面的代码以了解我的意思

In this way, domain usage goes hand-in-hand with the cluster module, since the master process can fork a new worker when a worker encounters an error. See the code below to understand what I mean

通过使用 Domain 工作进程使用 Cluster ,我们可以更恰当地反应,并以更大的安全性处理错误。

By using Domain, and the resilience of separating our program into multiple worker processes using Cluster, we can react more appropriately, and handle errors with much greater safety.

var cluster = require('cluster');
var PORT = +process.env.PORT || 1337;

if(cluster.isMaster) 
{
   cluster.fork();
   cluster.fork();

   cluster.on('disconnect', function(worker) 
   {
       console.error('disconnect!');
       cluster.fork();
   });
} 
else 
{
    var domain = require('domain');
    var server = require('http').createServer(function(req, res) 
    {
        var d = domain.create();
        d.on('error', function(er) 
        {
            //something unexpected occurred
            console.error('error', er.stack);
            try 
            {
               //make sure we close down within 30 seconds
               var killtimer = setTimeout(function() 
               {
                   process.exit(1);
               }, 30000);
               // But don't keep the process open just for that!
               killtimer.unref();
               //stop taking new requests.
               server.close();
               //Let the master know we're dead.  This will trigger a
               //'disconnect' in the cluster master, and then it will fork
               //a new worker.
               cluster.worker.disconnect();

               //send an error to the request that triggered the problem
               res.statusCode = 500;
               res.setHeader('content-type', 'text/plain');
               res.end('Oops, there was a problem!\n');
           } 
           catch (er2) 
           {
              //oh well, not much we can do at this point.
              console.error('Error sending 500!', er2.stack);
           }
       });
    //Because req and res were created before this domain existed,
    //we need to explicitly add them.
    d.add(req);
    d.add(res);
    //Now run the handler function in the domain.
    d.run(function() 
    {
        //You'd put your fancy application logic here.
        handleRequest(req, res);
    });
  });
  server.listen(PORT);
} 

虽然 Domain 正在取消弃用,并会因为Node的文档中所述的新替换而被删除

Though Domain is pending deprecation and will be removed as the new replacement comes as stated in Node's Documentation


此模块正在等待弃用。一旦替换API已完成,此模块将完全弃用。绝对必须具有域提供的功能的用户可能暂时依赖它,但应该期望将来迁移到不同的解决方案。

This module is pending deprecation. Once a replacement API has been finalized, this module will be fully deprecated. Users who absolutely must have the functionality that domains provide may rely on it for the time being but should expect to have to migrate to a different solution in the future.

但是直到没有引入新的替换,Domain with Cluster是Node Documentation建议的唯一好的解决方案。

But until the new replacement is not introduced, Domain with Cluster is the only good solution what Node Documentation suggests.

为了深入理解群集阅读

https://nodejs.org/api/domain.html#domain_domain 稳定性:0 - 已弃用

https://nodejs.org/api/cluster.html a>

https://nodejs.org/api/cluster.html

这篇关于如何防止node.js崩溃? try-catch不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆