使用 http.request 在 node.js 中捕获 ECONNREFUSED?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8381198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Catching ECONNREFUSED in node.js with http.request?
提问by Cera
I'm trying to catch ECONNREFUSED errors when using a HTTP client in node.js. I'm making requests like this:
在 node.js 中使用 HTTP 客户端时,我试图捕获 ECONNREFUSED 错误。我正在提出这样的请求:
var http = require('http');
var options = { host: 'localhost', port: '3301', path: '/', method: 'GET' };
http.request(options).on('response', function (res) {
// do some stuff
});
I can't figure out how to catch this error:
我不知道如何捕捉这个错误:
Error: connect ECONNREFUSED
at errnoException (net.js:614:11)
at Object.afterConnect [as oncomplete] (net.js:605:18)
If I do request.on('error', function () {});, it doesn't catch it. If I do it like this:
如果我这样做request.on('error', function () {});,它不会抓住它。如果我这样做:
var req = request.on(etc)
req.on('error', function blah () {});
Then I get TypeError: Object false has no method 'on'.
然后我得到TypeError: Object false has no method 'on'。
Do I really have to do a top-level uncaught error thing to deal with this? At the moment whatever I do my whole process quits out.
我真的必须做一个顶级未捕获的错误来处理这个问题吗?目前无论我做什么,我的整个过程都退出了。
Edit: I found some blog posts on how to do it by creating a connectionobject, calling requeston that, and then binding to errors on the connectionobject, but doesn't that make the entire http.request()shortcut useless?
编辑:我找到了一些关于如何通过创建connection对象,调用request它,然后绑定到connection对象上的错误来做到这一点的博客文章,但这不会使整个http.request()快捷方式无用吗?
回答by Ryan Olds
Any reason you're not using http://nodejs.org/docs/v0.6.5/api/http.html#http.requestas your base? Try this:
您不使用http://nodejs.org/docs/v0.6.5/api/http.html#http.request作为基础的任何原因?尝试这个:
var req = http.request(options, function(res) {
// Bind 'data', 'end' events here
});
req.on('error', function(error) {
// Error handling here
});
req.end();
回答by deezgz
Each call to http.request()returns its self.
So try it like this...
每次调用都会http.request()返回其自身。所以试试这样...
http.request(options.function(){}).on('error',function(){}).end();
回答by VorpalSword
I've got a solution for this, having tried all the suggestions on this (and many other) pages.
我有一个解决方案,已经尝试了这个(和许多其他)页面上的所有建议。
My client needs to detect a turnkey product that runs embedded windows. The client is served from a different machine to the turnkey.
我的客户需要检测运行嵌入式窗口的交钥匙产品。客户从不同的机器到交钥匙服务。
The turnkey can be in 3 states:
交钥匙可以处于 3 种状态:
- turned off
- booted into windows, but not running the turnkey app
- running the turnkey app
- 关闭
- 启动到 Windows,但没有运行交钥匙应用程序
- 运行交钥匙应用
My client sends a 'find the turnkey product' GET message to my nodejs/express service, which then tries to find the turnkey product via http.request. The behavior for each of the 3 use cases are;
我的客户向我的 nodejs/express 服务发送“找到交钥匙产品”GET 消息,然后该服务尝试通过 http.request 找到交钥匙产品。3 个用例中的每一个的行为是;
- timeout
- ECONNREFUSED - because the windows embedded phase of the turnkey is refusing connections.
- normal response to request (happy day scenario)
- 暂停
- ECONNREFUSED - 因为交钥匙的 windows 嵌入阶段拒绝连接。
- 对请求的正常响应(快乐的一天场景)
The code below handles all 3 scenarios. The trick to catching the ECONNREFUSED event was learning that its handler binds to the socket event.
下面的代码处理所有 3 种情况。捕获 ECONNREFUSED 事件的技巧是了解其处理程序绑定到套接字事件。
var http = require('http');
var express = require('express');
var url = require('url');
function find (req, res) {
var queryObj = url.parse(req.url, true).query;
var options = {
host: queryObj.ip, // client attaches ip address of turnkey to url.
port: 1234,
path: '/some/path',
}; // http get options
var badNews = function (e) {
console.log (e.name + ' error: ', e.message);
res.send({'ok': false, 'msg': e.message});
}; // sends failure messages to log and client
// instantiate http request object and fire it
var msg = http.request(options, function (response) {
var body = '';
response.on ('data', function(d) {
body += d;
}); // accumulate response chunks
response.on ('end', function () {
res.send({'ok': true, 'msg': body});
console.log('sent ok');
}); // done receiving, send reply to client
response.on('error', function (e) {
badNews(e);
}); // uh oh, send bad news to client
});
msg.on('socket', function(socket) {
socket.setTimeout(2000, function () { // set short timeout so discovery fails fast
var e = new Error ('Timeout connecting to ' + queryObj.ip));
e.name = 'Timeout';
badNews(e);
msg.abort(); // kill socket
});
socket.on('error', function (err) { // this catches ECONNREFUSED events
badNews(err);
msg.abort(); // kill socket
});
}); // handle connection events and errors
msg.on('error', function (e) { // happens when we abort
console.log(e);
});
msg.end();
}

