如何在node.js中捕获http客户端请求异常

发布于 2024-10-05 21:10:22 字数 567 浏览 5 评论 0原文

我有一个 node.js 应用程序,我想用它来检查特定站点是否已启动并返回正确的响应代码。我希望能够捕获由于域名未解析或请求超时而出现的任何错误。问题是这些错误会导致 Node 崩溃。我对整个异步编程方法很陌生,所以我不确定将 try/catch 语句放在哪里。

我有一个 ajax 调用,该调用转到 /check/site1 之类的内容。服务器端调用尝试建立连接的函数,然后返回状态代码。这是一个非常简单的函数,我将每一行都包装在 try/catch 中,但它从不捕获任何内容。就是这样:

function checkSite(url){
    var site = http.createClient(80, url);
    var request = site.request('GET', '/', {'host': url});
    request.end();
    return request;
  }

即使每一行都包含在 try/catch 中,我仍然会遇到未捕获的异常,例如 EHOSTUNREACH 等。我希望能够捕获这些并将其返回到 ajax 调用。

关于下一步尝试什么有什么建议吗?

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.

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:

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.

Any recommendations on what to try next?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

临走之时 2024-10-12 21:10:22

http.createClient 已被弃用。

以下是如何使用新的 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();

http.createClient has been deprecated.

Here is a quick example of how to handle errors using the 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();
缱倦旧时光 2024-10-12 21:10:22

不幸的是,目前还没有办法直接捕获这些异常,因为所有的事情都是在后台异步发生的。

您所能做的就是自己捕获 uncaughtException:

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');

在本例中(注意端口 800)记录:

{ message: 'ECONNREFUSED, Connection refused',
  stack: [Getter/Setter],
  errno: 111,
  syscall: 'connect' }

Node.js 仍在大力开发中,肯定会有很多进展在接下来的几个月里,现在的重点似乎是修复 3.x 的性能错误并使 API 稍微稳定,因为毕竟 Node.js 主要是一个服务器,因此吞吐量很重要。

不过,您可以提交错误,但请注意,崩溃等的优先级比功能要高得多,大多数新功能都是通过 fork pull requests 实现的。

另外,对于当前的 Node.js 路线图,请观看 Ryan Dahl(Node 的创建者)的演讲:
http://developer.yahoo.com/yui/theater/video .php?v=yuiconf2010-dahl

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:

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:

{ 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.

You can file a bug though, but be warned crashes etc. have way higher priority than features, and most new features make it in via fork pull requests.

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

霓裳挽歌倾城醉 2024-10-12 21:10:22

我在研究类似问题时偶然发现了另一个解决方案。如果由于任何原因无法建立连接,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");

当然,连接错误和请求的响应都是异步到达的,这意味着简单地返回请求是行不通的。相反,您必须将事件处理程序中的结果通知给调用者。

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:

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.

卷耳 2024-10-12 21:10:22

实际上,接受的答案更容易:

function checkSite(url){
var http = require('http');
var request = http.get(url,r=>{console.log("OK",r)}).on("error",e=>{
    console.log("ERROR",e)
})
}

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)
})
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文