[英]Error handling for http.get request in Node JS
var http = require('http');
var url = require('url');
var server = http.createServer(function(request, response) {
http.get('http://nodejs.org/dist/index.json', (res) => {
response.write("Inside http");
response.end();
}).on('error', function(e) {
console.log(e);
});
});
server.listen(3000);
On running above code, neither control goes inside http.get
nor it throws any error.What am I missing here in catching the error? 在上面的代码上运行时,控件都不会进入
http.get
也不会引发任何错误。在捕获错误时我在这里遗漏了什么?
Note : Server is created at 3000 注意:服务器创建于3000
add application level error handler in you app. 在您的应用中添加应用级错误处理程序。 If anything goes wrong, it will catch the error
如果发生任何错误,它将捕获错误
process.on('uncaughtException', function (err) {
// This should not happen
logger.error("Pheew ....! Something unexpected happened. This should be handled more gracefully. I am sorry. The culprit is: ", err);
});
It seems http.get should be placed in following way for it to work properly: 似乎应该按照以下方式放置http.get,以使其正常工作:
var http = require('http');
console.log('Before server');
var server = http.createServer(function(request, response) {
console.log('Request received');
});
server.listen(3000, function() {
http.get('http://nodejs.org/dist/index.json', (res) => {
console.log('Inside http');
})
.on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.