5

Node keeps quitting on me when a client refreshes while still loading a page (so the socket gets terminated, while I am still processing the request). The error:

[ERROR] - Error: socket hang up
   at createHangUpError (http.js:1472:15)
   at Socket.socketCloseListener (http.js:1522:23)
   at Socket.EventEmitter.emit (events.js:95:17)
   at TCP.close (net.js:465:12) (at lib/Maintenance.js:38)

I tried attaching on('error', ... to:

  1. req objects
  2. The return value of listen (I am using Express)
  3. The return value of my get, use and post methods.

And yet, I cannot seem to catch that error; it still gets thrown and none of my error handlers react. What could I possibly be missing?

Domi
  • 22,151
  • 15
  • 92
  • 122

3 Answers3

8

Attach error listeners to the socket objects

app.use(function(req, res, next) {
    req.socket.on("error", function() {

    });
    res.socket.on("error", function() {

    });
    next();
});
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Thanks! I'll try it in a few. What is the appropriate action to take? Can I just ignore it, or do I somehow have to somehow stop all actions on the `req` object? – Domi Jun 06 '14 at 11:12
  • @Domi correct thing would be to stop any processing you were doing for this particular req/res – Esailija Jun 06 '14 at 11:14
  • This seems so treacherous... Is there not a default solution to this? Like prepend every operation like so: `if (!req.errored) req.doSomething`? Or should `http` not have that build into all of `Request`'s methods? – Domi Jun 06 '14 at 11:30
  • Thanks btw, the socket error handlers are actually required. I ended up using [longjohn](https://github.com/mattinsler/longjohn), as recommended in [How to debug a socket hang up error in NodeJS?](http://stackoverflow.com/questions/10814481/how-to-debug-a-socket-hang-up-error-in-nodejs). Turns out, the error was thrown because I did not add an error listener to my instance of [http-proxy](https://github.com/nodejitsu/node-http-proxy). – Domi Jun 06 '14 at 18:27
  • 1
    @Esailija but why twice? – shabunc Sep 26 '14 at 00:15
  • @shabunc twice? i only see one event handler per obj (req vs res) – Kevin B Jan 18 '17 at 20:38
1

try catching error like this and see if it works..

app.use(function(err,req, res, next) {
    if(err)console.log(err);
    next();
});
azero0
  • 2,220
  • 3
  • 20
  • 31
0

In my case it hanged due to an error during jwt verify wasn't properly managed.

return res.status(403)   // issues code
return res.status(403).send(error)  // working code
cottontail
  • 10,268
  • 18
  • 50
  • 51
Shah Vipul
  • 625
  • 7
  • 11