web-dev-qa-db-ja.com

getaddrinfoENOTFOUNDをキャッチする方法

一部のデータを処理する前に確認する必要があるリンクのリストがあります。 http.getでヘッダーを確認すると、エラーが返されます。

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

このエラーを処理できず、プロセスを終了します。 res.on( "error")とhttp.getで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));
    });

}
12
Maxali

エラーメッセージに記載されているように、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' }
25
Paul Mougel

最上位レベルでは、次のことができます

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

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)
  });
0
Saurabh Mistry