在nodejs https.request中处理ECONNRESET [英] Handle ECONNRESET in nodejs https.request
问题描述
因此有时会出现网络或服务器问题,并且ECONNRESET会导致https.request失败。我认为正确的做法是重试指数延迟,从无延迟开始,直到数小时。但是,如果比较容易,我可以延迟5分钟。我读过一篇有关异步错误处理的文章,但找不到类似这样的简单示例的任何例子。请给我一个可行的例子吗?
谢谢!
So sometimes there is network or server issues and https.request fails with ECONNRESET. I think the proper thing to do would be to retry with exponential backoff delays, starting with none, and building up to several hours. But if it's easier I could just use a 5 minute delay. I've read an article on asynchronous error handling, but I haven't been able to find any examples for something simple like this. Could I get a working example please? Thanks!
推荐答案
只需附加一个错误
事件处理程序在请求对象上:
Just attach an error
event handler on the request object:
var req = https.request(...);
req.on('error', function(err) {
// handler `err` here ...
});
重试:
// waits 1 second on first error, then 2, then 4, then 8, etc.
function makeRequest(url, lastTimeout) {
lastTimeout || (lastTimeout = 500);
var req = https.request(url, ...);
req.on('error', function(err) {
console.error(err);
lastTimeout *= 2;
setTimeout(makeRequest, lastTimeout, url, lastTimeout);
});
}
// call function
makeRequest('https://google.com');
您可能会希望在重试上设置某种上限,所以它不会无限期重试。您还可以向 lastTimeout
添加随机毫秒数,以使每次的精确度都不那么精确。
You will probably want to put some kind of upper bound on the retries though, so it doesn't retry indefinitely. You could also add to lastTimeout
a random number of milliseconds to make it less exactly exponential every time.
这篇关于在nodejs https.request中处理ECONNRESET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!