我注意到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处理程序正在触发,但它仍然会崩溃。
答案 0 :(得分:1)
异常本身并未关闭程序,节点正在停止,因为事件队列中没有任何内容。
异常仍然会停止执行当前的函数/上下文,因此它永远不会到达http.createServer
。如果将错误移到http命令之外,它将按预期工作。 :)