Node.js:
var https = require("https");
var request = https.get("google/", function(response) {
console.log(response.statusCode);
});
request.on("error", function(error) {
console.log(error.message);
});
If I add https:// to the google domain name then I get the status code 200 as expected. As is, I would expect the error to be caught and an error message similar to "connect ECONNREFUSED" to be printed to the terminal console. Instead it prints the stacktrace to the terminal.
Node.js:
var https = require("https");
var request = https.get("google./", function(response) {
console.log(response.statusCode);
});
request.on("error", function(error) {
console.log(error.message);
});
If I add https:// to the google domain name then I get the status code 200 as expected. As is, I would expect the error to be caught and an error message similar to "connect ECONNREFUSED" to be printed to the terminal console. Instead it prints the stacktrace to the terminal.
Share Improve this question asked Jan 21, 2016 at 20:02 801Engi801Engi 1031 gold badge1 silver badge4 bronze badges 3- 1 Try printing just error, not error.message – Andrew Williamson Commented Jan 21, 2016 at 20:08
- 1 And why should the connection be refused ? – adeneo Commented Jan 21, 2016 at 20:14
-
Use
https
protocol likehttps://google.
instead ofgoogle.
. – Maxali Commented Jan 21, 2016 at 22:03
1 Answer
Reset to default 12If you look at the source for https.get()
, you can see that if the parsing of the URL fails (which it will when you only pass it "google./"
since that isn't a valid URL), then it throws synchronously:
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);
};
So, if you want to catch that particular type of error, you need a try/catch around your call to https.get()
like this:
var https = require("https");
try {
var request = https.get("google./", function(response) {
console.log(response.statusCode);
}).on("error", function(error) {
console.log(error.message);
});
} catch(e) {
console.log(e);
}