【问题标题】:How to catch getaddrinfo ENOTFOUND如何捕获 getaddrinfo ENOTFOUND
【发布时间】:2014-02-09 17:47:25
【问题描述】:

我有一个链接列表,在处理一些数据之前我需要检查这些链接。使用 http.get 检查标头返回错误:

events.js:72   
        throw er; // Unhandled 'error' event    
          ^    
Error: getaddrinfo ENOTFOUND       
    at errnoException (dns.js:37:11) 

我无法处理此错误,并退出该过程。我尝试了 res.on("error") 并尝试在 http.get 上尝试..catch,但没有任何效果。

下面是代码sn-p,和here is live example at runnable.com

//This is OK
getHeaders('http://google.com/404pag-that-does-not-exit');


//Here is the error.
//Uncoughtable error!
getHeaders('http://doesnotexistooooo.com');

function getHeaders(link){
    var _http = require("http");
    var myUrl = require("url");

    var qs=(myUrl.parse(link).search==null) ? "" : myUrl.parse(link).search ;
    var path=myUrl.parse(link).pathname;

    var options = {
        hostname: myUrl.parse(link).hostname,
        path: path+qs,
        method: 'HEAD'
    };
    _http.get(options, function(res) {
        res.on('error',function(e){
            console.log("Error: " + myUrl.parse(link).hostname + "\n" + e.message); 
            console.log( e.stack );
        });
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
    });

}

【问题讨论】:

标签: node.js http dns getaddrinfo


【解决方案1】:

您只需要处理error 事件,如错误消息中所述。根据the documentation

如果在请求期间遇到任何错误(可能是 DNS 解析、TCP 级别错误或实际 HTTP 解析错误),则会在返回的请求对象上发出“错误”事件。

这是一个用法示例:

var getRequest = _http.get(options, function(res) {
    // …
});
getRequest.on('error', function (err) {
    console.log(err);
});

产生:

$ node test.js
{ [Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND', errno: 'ENOTFOUND', syscall: 'getaddrinfo' }

【讨论】:

  • 也可以告诉我解决方案
  • 只是补充一点,同样的技术也适用于 NPM request 模块。
【解决方案2】:

在最顶层,你可以做到

process.on('uncaughtException', function(err) {
  console.log('### BIG ONE (%s)', err);
});

【讨论】:

    【解决方案3】:

    如果你使用request npm

    request
      .get('http://example.com/doodle.png')
      .on('response', function(response) {
        console.log(response.statusCode) // 200
        console.log(response.headers['content-type']) // 'image/png'
      })
      .on('error', function(err) {   // <------- add this 
        console.log(err)
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-15
      • 2017-10-16
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多