【问题标题】:How to catch node.js http error on nonexistent host?如何在不存在的主机上捕获 node.js http 错误?
【发布时间】:2012-01-29 05:19:13
【问题描述】:

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

requestToRemote = http.createClient(80, 'fjasdfhasdkfj.vvvxcz').request(
    method,
    path,
    headers
);

但我收到以下错误:

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)

我想捕捉这个错误,所以我尝试了 try/catch 并设置了一堆请求属性的错误侦听器,但没有一个有效。我怎样才能发现错误?

【问题讨论】:

    标签: http node.js error-handling


    【解决方案1】:

    您可以在运行代码之前尝试使用 dns 模块解析主机。

    http://nodejs.org/docs/latest/api/dns.html#dns.resolve

    【讨论】:

    • 这不是一个好的解决方案,因为它会涉及两次解析主机名。即使在缓存的情况下,仍然会有一个可以迅速增加的小惩罚,具体取决于您的应用程序的需要。当然,您可以在发出请求时使用网络地址而不是主机名,但是您必须自己处理指定主机的请求标头。
    【解决方案2】:

    看起来错误是从http.Client 抛出的,而不是请求。像这样的东西怎么样:

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

    仅供参考,http.createClient 已被弃用——以下内容应使用 get 便捷方法工作:

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

    【讨论】:

    • 如何在回调中使用res值来查看响应的文本是什么?
    • 这不是解决捕获不存在主机的问题,也不是dns解析问题。 the try catch 选项也不起作用。
    猜你喜欢
    • 2016-10-05
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2018-01-03
    相关资源
    最近更新 更多