Handle ECONNRESET retries using req.reusedSocket
masterWhen a server closes a connection during a keep-alive race, the client may throw an ECONNRESET error. agentkeepalive implements req.reusedSocket, which allows you to detect if the request was sent through a reused socket. If req.reusedSocket is true and the error is ECONNRESET, you can safely retry the request.
const http = require('http');
const HttpAgent = require('agentkeepalive').HttpAgent;
const agent = new HttpAgent();
const req = http
.get('http://localhost:3000', { agent }, (res) => {
// ... handle response
})
.on('error', (err) => {
// If the error happened on a reused socket, it's likely a keep-alive race
if (req.reusedSocket && err.code === 'ECONNRESET') {
// retry the request...
}
});