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

时间:2021-02-28 16:58:25

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.

我有一个节点。我想要使用的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调用。服务器端调用一个函数,该函数试图建立连接,然后返回状态码。这是一个非常简单的函数,我用一个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?

有什么建议吗?

3 个解决方案

#1


59  

http.createClient has been deprecated.

http。createClient已弃用。

Here is a quick example of how to handle errors using the new http.request:

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

#2


11  

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。如果由于任何原因无法建立连接,客户端会发出“错误”事件。如果处理此事件,则不会抛出异常:

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.

当然,连接错误和对请求的响应都是异步的,这意味着返回请求不会起作用。相反,您必须将事件处理程序内部的结果通知调用者。

#3


8  

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:

在这种情况下(注意端口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.

节点。js仍在大量开发中,未来几个月肯定会有很多进展,目前的重点似乎是修复3的性能缺陷。使API更稳定,因为毕竟是节点。js主要是一个服务器,所以吞吐量很重要。

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.

尽管你可以提交一个错误,但是要注意的是崩溃等问题比功能更重要,而且大多数新功能都是通过fork pull请求实现的。

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

也用于节点的当前路线图。下面是Ryan Dahl (Node的创建者)的讲话:http://developer.yahoo.com/yui/theater/video.php?v=yuiconf2010-dahl

#1


59  

http.createClient has been deprecated.

http。createClient已弃用。

Here is a quick example of how to handle errors using the new http.request:

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

#2


11  

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。如果由于任何原因无法建立连接,客户端会发出“错误”事件。如果处理此事件,则不会抛出异常:

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.

当然,连接错误和对请求的响应都是异步的,这意味着返回请求不会起作用。相反,您必须将事件处理程序内部的结果通知调用者。

#3


8  

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:

在这种情况下(注意端口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.

节点。js仍在大量开发中,未来几个月肯定会有很多进展,目前的重点似乎是修复3的性能缺陷。使API更稳定,因为毕竟是节点。js主要是一个服务器,所以吞吐量很重要。

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.

尽管你可以提交一个错误,但是要注意的是崩溃等问题比功能更重要,而且大多数新功能都是通过fork pull请求实现的。

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

也用于节点的当前路线图。下面是Ryan Dahl (Node的创建者)的讲话:http://developer.yahoo.com/yui/theater/video.php?v=yuiconf2010-dahl