801Engi 801Engi - 2 months ago 10
Javascript Question

Why is this basic Node.js error handling not working?

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.

Answer

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