2012-02-09 69 views
1

我注意到即使Node.js的崩溃对类型错误的捕获捕获的异常,这里的一些示例代码:的Node.js的类型错误甚至崩溃,而捕获捕获的异常

var http = require('http'); 

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

var test = []; 

// This causes the error because test[0] is undefined 
console.log(test[0].toLowerCase()); 

http.createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('Hello World\n'); 
}).listen(1337, "127.0.0.1"); 

有没有办法赶上错误并保持node.js运行。

更新:我应该提到uncaughtException处理程序在这种情况下触发,但它仍然崩溃后。

回答

1

异常本身并未关闭程序,节点停止,因为事件队列中没有任何内容。

异常仍然会停止当前函数/上下文的执行,所以它永远不会到达您的http.createServer。如果您将错误移动到http命令之外,它将按预期工作。 :)

+0

那么这是相当尴尬:) – 2012-02-09 18:14:51