为什么这个基本的Node.js错误处理不起作用? [英] Why is this basic Node.js error handling not working?

查看:84
本文介绍了为什么这个基本的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);
});

如果我添加https://到google域名,那么我会按预期得到状态码200 。就这样,我期望错误被捕获,并且类似于连接ECONNREFUSED的错误消息被打印到终端控制台。

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.

推荐答案

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

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

所以,如果你想抓住那个特定类型的错误,你需要一个try / catch调用 https.get()如下:

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

这篇关于为什么这个基本的Node.js错误处理不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆