如何阻止节点js服务器崩溃 [英] how to stop node js server from crashing
问题描述
我是节点js的新手。我试图创建一个简单的HTTP服务器。我按照着名的例子创建了一个'Hello World!'服务器,如下所示。
I am new to node js. I was trying to create a simple HTTP server. I followed the famous example and created a 'Hello World!' server as follows.
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
的错误而导致崩溃定义。我希望服务器仍然可以继续运行,并在遇到错误时正常报告错误。
Running this code would start the server properly as expected. But trying to access http://127.0.0.1:8080
would crash it by throwing an error that res1
is not defined. I would like to have the server still continue running and gracefully report errors whenever it encounters it.
我如何实现它?我尝试过try-catch,但这对我没有帮助:(
How do I achieve it? I tried try-catch but that isn't helping me :(
推荐答案
这里有很多评论。首先,为了使您的示例服务器正常工作,需要在使用之前定义handleRequest。
There are a bunch of comments here. First of all, for your example server to work, handleRequest needs to be defined BEFORE using it.
1-可以处理实际需要的,阻止进程退出的内容通过处理uncaughtException(文档)事件:
1- What you actually want, which is preventing the process to exit, can be handled by handling uncaughtException (documentation) 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){},例如:
2- I would recomment to use try{} catch(e) {} on your code, such as:
var handleRequest = function(req, res) {
try {
res.writeHead(200);
res1.end('Hello, World!\n');
} catch(e) {
res.writeHead(200);
res.end('Boo');
}
};
3-我猜这个例子只是一个例子而不是实际的代码,这是一个解析错误,可以预防。我提到这一点,因为你需要在异常捕获处理程序上没有解析错误。
3- I guess the example was just an example and not actual code, this is a parsing error that can be prevented. I mention this, since you NEED to NOT have parsing errors on Exception catch handlers.
4-请注意节点进程
将来会被域名取代
4- Please note that node process
is going to be replaced in the future with domain
5-我宁愿使用像表达这样的框架,而不是这样做。
5- I'd rather use a framework like express, than doing this stuff.
6-推荐讲座: StackOverflow - NodeJS异常处理的最佳实践
这篇关于如何阻止节点js服务器崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!