10

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

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.

3
  • 1
    Try printing just error, not error.message Commented Jan 21, 2016 at 20:08
  • 1
    And why should the connection be refused ? Commented Jan 21, 2016 at 20:14
  • Use https protocol like https://google.com instead of google.com. Commented Jan 21, 2016 at 22:03

1 Answer 1

12

If 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.com/" 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.com/", function(response) {
        console.log(response.statusCode);
    }).on("error", function(error) {
        console.log(error.message);
    });
} catch(e) {
    console.log(e);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.