我是第一次接触node js。我正在尝试创建一个简单的HTTP服务器。我遵循了这个著名的例子,创建了一个“Hello World!”服务器,如下所示。
var handleRequest = function(req, res) {
res.writeHead(200);
res1.end('Hello, World!\n');
};
require('http').createServer(handleRequest).listen(8080);
console.log('Server started on port 8080');运行此代码将按预期正确启动服务器。但是,尝试访问http://127.0.0.1:8080时会抛出未定义res1的错误,从而使其崩溃。我希望服务器仍然继续运行,并在遇到错误时优雅地报告错误。
我该如何实现它?我试着尝试捕捉,但这对我没有帮助:
发布于 2013-01-14 01:41:43
这里有一堆评论。首先,为了让示例服务器正常工作,需要在使用handleRequest之前对其进行定义。
1-阻止进程退出的实际需要可以通过处理uncaughtException (documentation)事件来处理:
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-请注意,未来将使用domain替换节点process
5-我更喜欢使用像express这样的框架,而不是做这些事情。
6-推荐讲座:StackOverflow - NodeJS best practice for exception handling
发布于 2014-03-15 21:32:24
我不是针对你的问题细节,而是你的问题的标题是关于防止Node服务器崩溃。您可以使用域,这可能会在抛出uncaughtException时防止您的服务器崩溃。
domain = require('domain'),
d = domain.create();
d.on('error', function(err) {
console.error(err);
});有关更多详细信息,请访问http://shapeshed.com/uncaught-exceptions-in-node/
此外,使用此方法还必须尝试捕获您的块。
发布于 2013-01-14 01:24:41
也许你应该在使用handleRequest之前定义它:
require('http').createServer(handleRequest).listen(8080);
function handleRequest(req, res) {
res.writeHead(200);
res1.end('Hello, World!\n');
};或
var handleRequest = function(req, res) {
res.writeHead(200);
res1.end('Hello, World!\n');
};
require('http').createServer(handleRequest).listen(8080);您应该确保res1也存在。
https://stackoverflow.com/questions/14306066
复制相似问题