【问题标题】:Dealing with node.js exceptions处理 node.js 异常
【发布时间】:2011-12-28 22:17:33
【问题描述】:

我们希望将 node.js 用于高度动态的项目。传统上,我们使用 Java,当遇到未处理的异常时,会引发错误,但 Web 应用程序(通常)会继续为其他请求提供服务。

但是,对于节点,相同的情况会导致进程终止。如果我们将这个系统部署到生产环境中并且由于未处理的异常而导致整个服务器崩溃,我不想去想会发生什么。

我想知道是否有教程/工具/等来帮助解决处理异常的问题。例如,有没有办法添加一个全局的 last-resort-type 异常?

【问题讨论】:

    标签: exception node.js


    【解决方案1】:
    process.on('uncaughtException', function (err){
      console.error(err)
    })
    

    【讨论】:

      【解决方案2】:

      正如提到的here,您会发现error.stack 提供了更完整的错误消息,例如导致错误的行号:

      process.on('uncaughtException', function (error) {
         console.log(error.stack);
      });
      

      【讨论】:

        【解决方案3】:

        你应该使用Node.js domains:

        响应抛出的错误最安全的方法是关闭进程。当然,在普通的 Web 服务器中,您可能会打开许多​​连接,并且因为其他人触发了错误而突然关闭这些连接是不合理的。

        更好的方法是向触发错误的请求发送错误响应,同时让其他人在正常时间完成,并停止在该工作人员中侦听新请求。

        链接页面包含示例代码,我在下面稍微简化了这些代码。它的工作方式如上所述。您可以以退出时自动重新启动的方式调用您的服务器,或者use the worker pattern from the full example

        var server = require('http').createServer(function(req, res) {
          var d = domain.create();
          d.on('error', function(er) {
            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();
        
              // try to 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() {
            // your application logic goes here
            handleRequest(req, res);
          });
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-12-27
          • 1970-01-01
          • 2011-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多