【发布时间】:2017-02-21 22:17:48
【问题描述】:
我有以下代码会产生问题:
var timeout_wrapper = function (req) {
return function () {
log.error('rest', 'Unable to contact service. Timed out.');
if (res.req) {
res.status(HttpStatus.INTERNAL_SERVER_ERROR).send('Timed out contacting service.');
}
req.abort();
};
};
var timeout;
var req = https.get(options, function (response) {
log.info('rest', 'Got response from service.');
clearTimeout(timeout);
if (response.statusCode === HttpStatus.NOT_FOUND) {
callback(false);
return;
}
if (response.statusCode === HttpStatus.NO_CONTENT) {
callback(true);
return;
}
log.error('rest', 'Service returned an undocumented status code: %s', response.statusCode);
res.status(HttpStatus.INTERNAL_SERVER_ERROR).send('Unable to contact service.');
}).on('error', function (e) {
clearTimeout(timeout);
log.error('rest', 'Unable to contact service. Got error: %s', e);
/*if (res.req) {
res.status(HttpStatus.INTERNAL_SERVER_ERROR).send('Unable to contact service.');
}*/
});
timeout = setTimeout(timeout_wrapper(req), 10000);
我联系的服务经常超时(但我无法控制)。所以我创建了一个超时函数,它可以工作(客户端确实在接收 res.status(HttpStatus.INTERNAL_SERVER_ERROR).send('Timed out contacting service.'); ),但请求没有中止。 .on('error', ...) 会在一段时间后使用以下堆栈跟踪调用:
ERR! rest Error: socket hang up
ERR! rest at createHangUpError (http.js:1472:15)
ERR! rest at CleartextStream.socketCloseListener (http.js:1522:23)
ERR! rest at CleartextStream.EventEmitter.emit (events.js:117:20)
ERR! rest at tls.js:696:10
ERR! rest at process._tickCallback (node.js:415:13)
ERR! rest Unable to contact service. Got error: %s { [Error: socket hang up] code: 'ECONNRESET' }
我以为这是一个简单的 HTTPS GET 请求,而不是套接字,为什么我的超时函数中没有中止请求?
【问题讨论】: