有没有可能通过尝试连接到一个错误的url来捕获生成的exception?

使用节点http包似乎不可能赶上打开一个错误的URL造成的exception。 这是一个问题,因为它杀死了我想保证永远活着的群集

这里是代码:(使用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); } } 

这是我如何testing它

 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。 它从来没有被抓住

当为请求提供error handling程序时,它适用于我:

 req.on('error', errorHandler); 

我看到你也是这样做的,但是你在发布之后设置了它

 req.end(); 

你可以尝试在附加error handling程序后发出end()吗?

作为一个侧面说明,我真的推荐请求 ,因为它处理这样的问题与合理的默认值。 与之合作真是一件轻而易举的事情。

编辑:这是一个简单的例子,显示附加一个error handling程序让我处理ENOENT / ENOTFOUND错误:

 var http = require('http'); var req = http.request({hostname: 'foo.example.com'}, function(err, res) { if(err) return console.error(err); console.log('got response!'); }); req.on('error', function(err) { console.error('error!', err); }); 

另一个有价值的信息:我不知道它如何适应光纤,但一般来说,你不应该throw nodejsasynchronous代码。 它很less按照你想要的方式工作。 相反,使用传递任何错误作为下一个callback的第一个参数的标准做法,并在有意义的地方处理错误(通常,在调用链中最高处,您可以对其进行合理的处理)。

你可以刮页的错误代码。