【问题标题】:Why is this basic Node.js error handling not working?为什么这个基本的 Node.js 错误处理不起作用?
【发布时间】:2016-04-28 06:11:16
【问题描述】:

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

如果我将 https:// 添加到 google 域名,那么我会按预期获得状态代码 200。照原样,我希望错误被捕获,并且类似于“connect ECONNREFUSED”的错误消息被打印到终端控制台。相反,它将堆栈跟踪打印到终端。

【问题讨论】:

  • 尝试只打印 error,而不是 error.message
  • 为什么要拒​​绝连接?
  • 使用https 协议如https://google.com 而不是google.com

标签: javascript node.js error-handling


【解决方案1】:

如果你查看source for 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);
};

因此,如果您想捕获该特定类型的错误,您需要在调用 https.get() 时使用 try/catch,如下所示:

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

【讨论】:

    猜你喜欢
    • 2021-10-29
    • 1970-01-01
    • 2015-09-22
    • 2015-08-16
    • 1970-01-01
    • 2014-03-07
    • 2020-08-17
    • 2020-03-10
    • 1970-01-01
    相关资源
    最近更新 更多