我是 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
未定义的错误,从而使它崩溃。我想让服务器继续运行并在遇到错误时优雅地报告错误。
我如何实现它?我试过 try-catch 但这对我没有帮助:(
最佳答案
这里有一堆评论。首先,为了让您的示例服务器正常工作,需要在使用它之前定义 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- 请注意, Node process
将来会被替换为 domain
5- 我宁愿使用像 express 这样的框架,而不是做这些事情。
6- 推荐讲座:StackOverflow - NodeJS best practice for exception handling
关于javascript - 如何阻止 Node js服务器崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14306066/