I have an app that will require HTTP requests to a primary and secondary URL. When the primary URL goes down I need to be able to handle this gracefully and failover to the secondary URL. I already have the failover function running, but am running into an issue handling the timeouts.
After some searching I found that Node does not have a default timeout so I have set one up. The problem I am running into is that after setting the request time out that the socket stays open. If I destroy or abort the request it throws an error that it was exited too soon. I know that I can handle this with a req.on('error'), but I want to be able to use that for other error handling as well if necessary. I have tried a couple of ways of running the time out.
The first is to set a timeout on the socket and destroy it. This causes a socket hang up error.
var req= https.request(options, function(res){
//Handle response based on return code
});
req.on('socket', function(socket){
socket.setTimeout(10000);
socket.on('timeout', function(){
socket.destroy();
self.emit("runAgain");
})
});
req.on('error', function(err){
console.log(err);
});
req.end();
The other way I tried is to set a time out on the request. This caused an ECONNRESET error.
req.setTimeout(100, function(){
req.destroy();
console.log('request destroyed');
})
I'm looking for the best way to handle this so that I don't have to set a time out and then catch an error if at all possible.