2016-01-21 19 views
5

node.js:Bu temel Node.js hatası neden çalışmıyor?

Ben https eklerseniz
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); 
}); 

: // google alan adına sonra beklendiği gibi durum kodu 200 olsun. Olduğu gibi, hatanın yakalanacağını ve terminal konsoluna yazdırılmak üzere "ECONNREFUSED" kaynağına benzer bir hata mesajı beklerim. Bunun yerine stacktrace'i terminale yazdırır. Eğer source for https.get() bakarsak

+1

deneyin baskı sadece * hata *, değil * Error.message * –

+1

Ve neden bağlantı reddedilmeli? d – adeneo

+0

'google.com' yerine' https' protokolünü https: // google.com' gibi kullanın. – Maxali

cevap

9

, daha sonra zaman uyumlu atar, URL ayrıştırma başarısız olursa (yani geçerli bir URL değil çünkü sadece "google.com/" geçmek zaman geleceğine) görebiliriz:

Eğer hata söz konusu türünü yakalamak istiyorsanız
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); 
}; 

Yani, böyle https.get() çağrınızda etrafında bir try/catch gerekir:

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); 
}