18

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

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

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

下面是代码片段,这里是 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));
    });

}
4

3 回答 3

31

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

如果在请求期间遇到任何错误(可能是 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' }
于 2014-02-09T18:52:28.640 回答
2

在最高级别,你可以做

process.on('uncaughtException', function(err) {
  console.log('### BIG ONE (%s)', err);
});
于 2019-01-14T15:24:34.083 回答
0

如果您使用请求 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)
  });
于 2019-05-12T07:57:10.213 回答