如何在不存在的主机上捕获node.js http错误?

Flu*_*ffy 15 error-handling http node.js

当我尝试使用该http模块访问不存在的主机时,如下所示:

requestToRemote = http.createClient(80, 'fjasdfhasdkfj.vvvxcz').request(
    method,
    path,
    headers
);
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: getaddrinfo ENOENT
    at errnoException (dns.js:31:11)
    at Object.onanswer [as oncomplete] (dns.js:140:16)
Run Code Online (Sandbox Code Playgroud)

我想捕获这个错误,所以我尝试了try/catch并设置了一堆请求属性的错误监听器,但是没有一个工作.我怎样才能发现错误?

mik*_*ike 14

看起来是错误http.Client,而不是请求.怎么样的:

var site = http.createClient(80, host);
site.on('error', function(err) {
    sys.debug('unable to connect to ' + host);
});
var requestToRemote = site.request(...);
Run Code Online (Sandbox Code Playgroud)

仅供参考,http.createClient已被弃用 - 以下应使用获取方便方法:

http.get({host: host}, function(res) {
    ...
}).on('error', function(e) {
    console.log("Got error: " + e.message);
});
Run Code Online (Sandbox Code Playgroud)