为什么这个基本的Node.js错误处理不起作用?

801*_*ngi 7 javascript error-handling node.js

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);
});
Run Code Online (Sandbox Code Playgroud)

如果我将https://添加到Google域名,那么我会按预期获得状态代码200.因此,我希望捕获错误并将类似于"connect ECONNREFUSED"的错误消息打印到终端控制台.相反,它将堆栈跟踪打印到终端.

jfr*_*d00 11

如果您查看源代码https.get(),您可以看到,如果URL的解析失败(当您只传递它时将会解析,"google.com/"因为它不是有效的URL),那么它会同步抛出:

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);
};
Run Code Online (Sandbox Code Playgroud)

所以,如果你想捕获那种特殊类型的错误,你需要在你的调用中尝试一下try/catch,https.get()如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)