2016-01-21 8 views
5

のNode.js:なぜこの基本的なNode.jsエラー処理が機能しないのですか?

var https = require("https"); 


var request = https.get("google.com/", function(response) { 
    console.log(response.statusCode); 
}); 

request.on("error", function(error) { 
     console.log(error.message); 
}); 

私がhttps追加する場合:Googleのドメイン名に//を予想通り、私はステータスコード200を取得します。つまり、エラーが検出され、「ECONNREFUSEDに接続する」のようなエラーメッセージがターミナルコンソールに出力されることが予想されます。その代わりにスタックトレースを端末に出力します。

+1

はちょうど*エラー*、ありません* error.message *を印刷してみてください –

+1

なぜ接続が拒否されるべきかd? – adeneo

+0

'google.com'ではなく' https:// google.com'のような 'https'プロトコルを使います。 – Maxali

答えて

9

あなたはsource for https.get()を見れば、あなたはURLの構文解析は、(それが有効なURLではありませんので、それはあなただけそれ"google.com/"に合格するときに)失敗した場合、それが同期投げることがわかります。

exports.get = function(options, cb) { 
    var req = exports.request(options, cb); 
    req.end(); 
    return req; 
}; 

exports.request = function(options, cb) { 
    if (typeof options === 'string') { 
    options = url.parse(options); 
    if (!options.hostname) { 
     throw new Error('Unable to determine the domain name'); 
    } 
    } else { 
    options = util._extend({}, options); 
    } 
    options._defaultAgent = globalAgent; 
    return http.request(options, cb); 
}; 

エラーの特定のタイプをキャッチしたいのであれば、あなたはこのようなhttps.get()へお電話の周りのtry/catchを必要とする:

var https = require("https"); 

try { 
    var request = https.get("google.com/", function(response) { 
     console.log(response.statusCode); 
    }).on("error", function(error) { 
     console.log(error.message); 
    }); 
} catch(e) { 
    console.log(e); 
} 
関連する問題