如何在 node.js 中捕获 http 客户端请求异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4328540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to catch http client request exceptions in node.js
提问by mattmcmanus
I've got a node.js app that I want to use to check if a particular site is up and returning the proper response code. I want to be able to catch any errors that come up as the domain name isn't resolving or the request is timing out. The problem is is that those errors cause Node to crap out. I'm new to this whole asynchronous programming methodology, so I'm not sure where to put my try/catch statements.
我有一个 node.js 应用程序,我想用它来检查特定站点是否已启动并返回正确的响应代码。我希望能够捕获由于域名未解析或请求超时而出现的任何错误。问题是这些错误会导致 Node 崩溃。我是整个异步编程方法的新手,所以我不确定把我的 try/catch 语句放在哪里。
I have an ajax call that goes to something like /check/site1. Server side that calls a function which attempts to make a connection and then return the statusCode. It's a very simple function, and I've wrapped each line in a try/catch and it never catches anything. Here it is:
我有一个类似 /check/site1 的 ajax 调用。服务器端调用一个函数,该函数尝试建立连接,然后返回 statusCode。这是一个非常简单的函数,我将每一行都包含在一个 try/catch 中,但它永远不会捕获任何东西。这里是:
function checkSite(url){
var site = http.createClient(80, url);
var request = site.request('GET', '/', {'host': url});
request.end();
return request;
}
Even with each of those lines wrapped in a try/catch, I will still get uncaught exceptions like EHOSTUNREACH and so on. I want to be able to catch those and return that to the ajax call.
即使每一行都包含在 try/catch 中,我仍然会遇到诸如 EHOSTUNREACH 之类的未捕获异常。我希望能够捕捉到这些并将其返回给 ajax 调用。
Any recommendations on what to try next?
关于下一步尝试的任何建议?
回答by robertjd
http.createClienthas been deprecated.
http.createClient已被弃用。
Here is a quick example of how to handle errors using the new http.request:
以下是如何使用 new 处理错误的快速示例http.request:
var http = require("http");
var options = {
host : "www.example.com"
};
var request = http.request(options, function(req) {
...
});
request.on('error', function(err) {
// Handle error
});
request.end();
回答by Sarah Roberts
I stumbled across another solution while I was researching a similar problem. http.Client emits an 'error' event if a connection can't be established for any reason. If you handle this event then the exception won't be thrown:
在研究类似问题时,我偶然发现了另一个解决方案。如果由于任何原因无法建立连接,http.Client 会发出“错误”事件。如果您处理此事件,则不会抛出异常:
var http = require('http');
var sys = require('sys');
function checkSite(url) {
var site = http.createClient(80, url);
site.on('error', function(err) {
sys.debug('unable to connect to ' + url);
});
var request = site.request('GET', '/', {'host': url});
request.end();
request.on('response', function(res) {
sys.debug('status code: ' + res.statusCode);
});
}
checkSite("www.google.com");
checkSite("foo.bar.blrfl.org");
Of course, the connection error and the response to the request both arrive asynchronously, meaning that simply returning the request won't work. Instead, you'd have to notify the caller of the results from within the event handlers.
当然,连接错误和对请求的响应都是异步到达的,这意味着简单地返回请求是行不通的。相反,您必须从事件处理程序中通知调用者结果。
回答by Ivo Wetzel
Unfortunately, at the moment there's no way to catch these exceptions directly, since all the stuff happens asynchronously in the background.
不幸的是,目前还没有办法直接捕获这些异常,因为所有的事情都是在后台异步发生的。
All you can do is to catch the uncaughtException's on your own:
您所能做的就是自己捕获uncaughtException's :
var http = require('http');
function checkSite(url){
var site = http.createClient(800, url);
var request = site.request('GET', '/', {'host': url});
request.end();
return request;
}
process.on('uncaughtException', function (err) {
console.log(err);
});
checkSite('http://127.0.0.1');
Which in this case (notice port 800) logs:
在这种情况下(注意端口 800)日志:
{ message: 'ECONNREFUSED, Connection refused',
stack: [Getter/Setter],
errno: 111,
syscall: 'connect' }
Node.js is still under heavy development and there sure will be a lot of progress in the next couple of months, right now focus seem to be on fixing performance bugs for 3.x and making the API somewhat stable, because after all Node.js is mainly a server so throughput matters.
Node.js 仍在大力开发中,在接下来的几个月里肯定会有很多进展,现在的重点似乎是修复 3.x 的性能错误并使 API 变得有些稳定,因为毕竟 Node.js Node.js 主要是一个服务器,所以吞吐量很重要。
You can file a bugthough, but be warned crashes etc. have way higher priority than features, and most new features make it in via fork pull requests.
您可以提交错误,但要注意崩溃等。比功能具有更高的优先级,并且大多数新功能通过 fork 拉取请求进入。
Also for the current Roadmap of Node.js watch this talk by Ryan Dahl (Node's Creator):
http://developer.yahoo.com/yui/theater/video.php?v=yuiconf2010-dahl
对于 Node.js 当前的路线图,请观看 Ryan Dahl(Node 的创建者)的演讲:http:
//developer.yahoo.com/yui/theater/video.php?v=yuiconf2010-dahl
回答by Zibri
Actually it's even easier that the accepted answer:
实际上,接受的答案更容易:
function checkSite(url){
var http = require('http');
var request = http.get(url,r=>{console.log("OK",r)}).on("error",e=>{
console.log("ERROR",e)
})
}

