如何阻止 Node.js 服务器崩溃

2024-05-18

我是节点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 来处理(文档 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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何阻止 Node.js 服务器崩溃 的相关文章

随机推荐