Josh
Josh

Reputation: 142

Handle ECONNRESET in nodejs https.request

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!

Upvotes: 0

Views: 3574

Answers (1)

mscdex
mscdex

Reputation: 106696

Just attach an error event handler on the request object:

var req = https.request(...);
req.on('error', function(err) {
  // handler `err` here ...
});

With retries:

// 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');

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.

Upvotes: 1

Related Questions