这里有一堆评论。首先,为了让您的示例服务器正常工作,需要在使用之前定义handleRequest。
1-您真正想要的,即阻止进程退出,可以通过处理 uncaughtException 来处理(文档 http://nodejs.org/api/process.html#process_event_uncaughtexception) event:
var handleRequest = function(req, res) {
res.writeHead(200);
res1.end('Hello, World!\n');
};
var server = require('http').createServer(handleRequest);
process.on('uncaughtException', function(ex) {
// do something with exception
});
server.listen(8080);
console.log('Server started on port 8080');
2-我建议在您的代码上使用 try{} catch(e) {},例如:
var handleRequest = function(req, res) {
try {
res.writeHead(200);
res1.end('Hello, World!\n');
} catch(e) {
res.writeHead(200);
res.end('Boo');
}
};
3-我想这个例子只是一个例子,而不是实际的代码,这是一个可以防止的解析错误。我提到这一点,因为您不需要在异常捕获处理程序上出现解析错误。
4-请注意该节点process
将来将会被替换为domain http://nodejs.org/api/domain.html
5-我宁愿使用像这样的框架express http://expressjs.com/,而不是做这些事情。
6- 推荐讲座:StackOverflow - NodeJS 异常处理的最佳实践 https://stackoverflow.com/questions/7310521/node-js-best-practice-exception-handling