node.js 在发出 http 请求时区分错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19322248/
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
node.js distinguishing errors when making http request
提问by Heptic
My node.js application is using http.requestto the REST API http://army.gov/launch-nukesand I need to distinguish between three possible cases:
我的 node.js 应用程序正在使用http.requestREST API http://army.gov/launch-nukes,我需要区分三种可能的情况:
Success-- The server replies in the affirmative. I know my enemies are destroyed.Failure-- Either I have received error from the server, or was unable to connect to server. I still have enemies.Unknown-- After establishing a connection to the server, I have sent the request -- but not sure what happened. This could mean the request never made it to the server, or the server response to me never made it. I may or may not have just started a world war.
Success-- 服务器是肯定的回答。我知道我的敌人被摧毁了。Failure-- 我从服务器收到错误,或者无法连接到服务器。我还有敌人。Unknown--与服务器建立连接后,我已发送请求 -- 但不确定发生了什么。这可能意味着请求从未发送到服务器,或者服务器对我的响应从未发送。我可能刚刚开始了一场世界大战,也可能没有。
As you can see, it's very important for me to distinguish the Failureand Unknowncase, as they have very different consequences and different actions I need to take.
如您所见,区分Failure和Unknown案例对我来说非常重要,因为它们具有非常不同的后果和我需要采取的不同行动。
I would also very much like to use http Keep-Alive -- as what can I say, I'm a bit of a war-monger and plan on making lots of requests in bursts (and then nothing for long periods of time)
我也非常想使用 http Keep-Alive——我可以说,我有点喜欢War,并计划突然发出大量请求(然后很长一段时间没有任何请求)
--
——
The core of the question is how to separate a connection-error/time-out (which is a Failure) from an error/timeout that occurs after the request is put on the wire (which is an Unknown).
问题的核心是如何将连接错误/超时(即Failure)与在将请求放入线路后发生的错误/超时(即)分开Unknown。
In psuedo-code logic I want this:
在伪代码逻辑中,我想要这个:
var tcp = openConnectionTo('army.gov') // start a new connection, or get an kept-alive one
tcp.on('error', FAILURE_CASE);
tcp.on('connectionEstablished', function (connection) {
var req = connection.httpGetRequest('launch-nukes');
req.on('timeout', UNKNOWN_CASE);
req.on('response', /* read server response and decide FAILURE OR SUCCESS */);
}
)
回答by kamituel
Here is an example:
下面是一个例子:
var http = require('http');
var options = {
hostname: 'localhost',
port: 7777,
path: '/',
method: 'GET'
};
var req = http.request(options, function (res) {
// check the returned response code
if (('' + res.statusCode).match(/^2\d\d$/)) {
// Request handled, happy
} else if (('' + res.statusCode).match(/^5\d\d$/))
// Server error, I have no idea what happend in the backend
// but server at least returned correctly (in a HTTP protocol
// sense) formatted response
}
});
req.on('error', function (e) {
// General error, i.e.
// - ECONNRESET - server closed the socket unexpectedly
// - ECONNREFUSED - server did not listen
// - HPE_INVALID_VERSION
// - HPE_INVALID_STATUS
// - ... (other HPE_* codes) - server returned garbage
console.log(e);
});
req.on('timeout', function () {
// Timeout happend. Server received request, but not handled it
// (i.e. doesn't send any response or it took to long).
// You don't know what happend.
// It will emit 'error' message as well (with ECONNRESET code).
console.log('timeout');
req.abort();
});
req.setTimeout(5000);
req.end();
I recommend you play with it using netcat, ie.:
我建议你使用 netcat 来玩它,即:
$ nc -l 7777
// Just listens and does not send any response (i.e. timeout)
$ echo -e "HTTP/1.1 200 OK\n\n" | nc -l 7777
// HTTP 200 OK
$ echo -e "HTTP/1.1 500 Internal\n\n" | nc -l 7777
// HTTP 500
(and so on...)
(等等...)
回答by Zeke Alexandre Nierenberg
This is typically in the APIs status code. In the request package you can access it like this
这通常在 API 状态代码中。在请求包中,您可以像这样访问它
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the google web page.
}
})
response.statusCodebeing 200 means that it worked. 500 would be failure. Unknown would be the callback never being called.
response.statusCode为 200 意味着它有效。500 将是失败的。未知将是永远不会被调用的回调。
If the API you're describing doesn't follow standard response codes, I don't know. You'll have to look at the docs.
如果您描述的 API 不遵循标准响应代码,我不知道。您必须查看文档。

