如何捕获getaddrinfo ENOTFOUND [英] How to catch getaddrinfo ENOTFOUND

查看:244
本文介绍了如何捕获getaddrinfo ENOTFOUND的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of links that I need to check before processing some data. Checking headers with http.get returns error:

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

我无法处理此错误,并退出该过程。我试过res.on(错误)和try.catch在http.get,但没有任何作用。

I cannot handle this error, and exits the process. I tried res.on("error") and try..catch on http.get but nothing works.

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

}


推荐答案

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

You just need to handle the error event, as stated in the error message. According to the documentation:


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

If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object.

以下是使用示例:

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' }

这篇关于如何捕获getaddrinfo ENOTFOUND的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆