node.js 区分发出 http 请求时的错误

2024-03-24

我的node.js应用程序正在使用http.request到 REST APIhttp://army.gov/launch-nukes我需要区分三种可能的情况:

  • Success-- 服务器回复肯定。我知道我的敌人已经被消灭了。
  • Failure-- 要么我从服务器收到错误,或无法连接到服务器。我还有敌人。
  • Unknown -- 与服务器建立连接后,我已发送请求 - 但不确定发生了什么。这可能意味着请求从未到达服务器,或者服务器对我的响应从未到达。我可能刚刚开始了一场世界大战,也可能没有。

正如你所看到的,区分这些对我来说非常重要Failure and Unknown情况,因为它们会产生非常不同的后果,并且我需要采取不同的行动。

我也非常想使用http Keep-Alive——我能说的是,我有点好战,并计划突发发出大量请求(然后很长一段时间没有任何请求)

--

问题的核心是如何分离连接错误/超时(这是一个Failure)来自将请求放在线路上之后发生的错误/超时(这是一个Unknown).

在伪代码逻辑中我想要这样:

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

这是一个例子:

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

我建议你使用 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

(等等...)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

node.js 区分发出 http 请求时的错误 的相关文章

随机推荐