Riddhesh Markandeya
Riddhesh Markandeya

Reputation: 589

Can't catch socket hang up error of request which crashes the node server

I have a sails server which is acting as proxy(for elasticsearch). Client server(kibana) has req timeout of 30s, when it calls a long request to proxy which takes around 50s time, it times out but that raises socket hang up error in the server and it crashes.

I can increase the client timeout(which I don't feel is best), but how to catch this error?

Proxy code looks like:

const request = require('request');

function proxyRequest(req, res, esUrl) {
  let esReq = request({
    url: esUrl,
    method: req.method
  });
  esReq.on('error', function handleError(err) {
    console.log('Got error', err);
    res.json(500, {
      error: err
    });
  });

  return req.pipe(esReq).pipe(res);
}

Above error event listener on esReq is not catching the error, I have tried adding listeners on req and res as well but doesn't work.

Whole error is:

Error: socket hang up
at createHangUpError (_http_client.js:253:15)
at Socket.socketOnEnd (_http_client.js:345:23)
at emitNone (events.js:91:20)
at Socket.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)

How to catch this error and handle it?

Upvotes: 0

Views: 1215

Answers (1)

Riddhesh Markandeya
Riddhesh Markandeya

Reputation: 589

The solution, to listen on error event was correct. In my case requests were proxied twice at two different places and at one place there was no error listener and that's where the server was crashing. After finding that out just adding the error listener like above worked.

Upvotes: 1

Related Questions