最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is this basic Node.js error handling not working? - Stack Overflow

programmeradmin3浏览0评论

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 like https://google. instead of google.. – Maxali Commented Jan 21, 2016 at 22:03
Add a ment  | 

1 Answer 1

Reset to default 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./" 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);
}
发布评论

评论列表(0)

  1. 暂无评论