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

查看:16
本文介绍了如何捕获 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("error") 并尝试..catch on 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 + "
" + e.message); 
            console.log( e.stack );
        });
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
    });

}

推荐答案

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

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

如果在请求过程中遇到任何错误(无论是 DNS 解析、TCP 级别错误还是实际的 HTTP 解析错误),都会在返回的请求对象上发出 'error' 事件.

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天全站免登陆