使用 node http 包似乎无法捕获由打开错误 URL 引起的异常。这是一个问题,因为它会杀死我的集群,我想保证它会永远存在
这是代码:(使用fibers.promise)
function openConnection(dest, port, contentType, method, throwErrorOnBadStatus)
{
  "use strict";
  assert.ok(dest, "generalUtilities.openConnection: dest is null");
  //dest = dest.replace('//','/');
  console.log('opening connection: ' + dest + " contentType: " + contentType);
  var prom = promise(),
    errProm = promise(),
    ar = [],
    urlParts = url.parse(dest),
    httpClient,
    req,
    got,
    res;
  //console.log('urlParts.port: ' + urlParts.port);
  if (port) {
    urlParts.port = port;
  } else if (!urlParts.port) {
    urlParts.port = 80;
  }
  if (contentType) {
    urlParts.accept = contentType;
  } else {
    urlParts.contentType = 'text/html';
  }
  if (!urlParts.method) {
    if (method) {
      urlParts.method = method;
    } else {
      urlParts.method = 'GET';
    }
  }
  try {
    httpClient = http.createClient(urlParts.port, urlParts.hostname);
    req = httpClient.request(urlParts.method, urlParts.path, urlParts);
  //console.log('req: ' + req);
  //if (req.connection) {
  //  req.connection.setTimeout(HTTP_REQUEST_TIMEOUT);
  //}
  //else {
  //  throw new Error ("No Connection Established!");
  //}
      req.end();
    req.on('response', prom);
    req.on('error', errProm);
    got = promise.waitAny(prom, errProm);
    if (got === errProm) {
      //assert.ifError(errProm.get(), HTTP_REQUEST_TIMEOUT_MSG + dest);
      throw new Error(HTTP_REQUEST_TIMEOUT_MSG + dest + ': ' + got.get());
    }
    res = prom.get();
    ar.res = res;
    ar.statusCode = res.statusCode;
    if (ar.statusCode >= 300 && throwErrorOnBadStatus) {
      assert.ifError("page not found!");
    }
    return ar;
  }
  catch (err) {
    console.log(err);
  }
}
这就是我测试它的方法
var promise = require('fibers-promise');
var gu = require("../src/utils/generalutilities.js");
var brokenSite = 'http://foo.bar.com:94//foo.js';
promise.start(function () {
  try {
    gu.openConnection(brokenSite, null, null, "GET", true);
  }
  catch (err) {
    console.log('got: ' + err);
  }
});
当我运行此代码时,我得到:
错误:getaddrinfo ENOENT。它永远不会被 try catch 捕获