Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 533
801Engi Avatar asked Jan 21 '16 20:01

801Engi


1 Answers

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);
}
like image 78
jfriend00 Avatar answered Oct 15 '22 01:10

jfriend00