63

I am getting the following error:

events.js:48
        throw arguments[1]; // Unhandled 'error' event
        ^
Error: socket hang up
    at createHangUpError (http.js:1091:15)
    at Socket.onend (http.js:1154:27)
    at TCP.onread (net.js:363:26)

In node v0.6.6, my code has multiple http.request and .get calls. Please suggest ways to track what causes the socket hang up, and on which request/call it is. Thank you

Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115
user971956
  • 3,088
  • 7
  • 30
  • 47
  • You might solve by restarting the server, we are using pm2 when we get the above error we do `pm2 restart all`. – 151291 Feb 09 '19 at 05:14

5 Answers5

46

Quick and dirty solution for development:

Use longjohn, you get long stack traces that will contain the async operations.

Clean and correct solution: Technically, in node, whenever you emit an 'error' event and no one listens to it, it will throw. To make it not throw, put a listener on it and handle it yourself. That way you can log the error with more information.

To have one listener for a group of calls you can use domains and also catch other errors on runtime. Make sure each async operation related to http(Server/Client) is in different domain context comparing to the other parts of the code, the domain will automatically listen to the error events and will propagate it to its own handler. So you only listen to that handler and get the error data. You also get more information for free.(Domains are depreceated).

As Mike suggested you can also set NODE_DEBUG=net or use strace. They both provide you what is node doing internally.

danronmoon
  • 3,814
  • 5
  • 34
  • 56
Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115
  • And then see http://stackoverflow.com/questions/543738/go-to-character-in-vim for how to locate the "pos" that is given in the trace. – Jeff May 12 '15 at 17:27
  • 2
    Warning: node domains are currently [deprecated](https://nodejs.org/api/domain.html). – Daniel Griscom Nov 22 '17 at 01:44
  • Can you show example code for how to "handle it yourself"? How do I print all the relevant stack trace info? – Daniel Kaplan Oct 20 '21 at 17:26
  • Basically add an error handler and do the necessary logic that should happen in case of error, most of the time you simply want to log socket hang up errors. I would suggest passing it to your log handler, hopefully it supports printing errors stacktraces, but if you were to do it yourself it's normally as simple as `console.log(error) ` – Farid Nouri Neshat Oct 20 '21 at 19:08
26

Additionally, you can set the NODE_DEBUG environment variable to net to get information about what all the sockets are doing. This way you can isolate which remote resource is resetting the connection.

Mike
  • 920
  • 1
  • 9
  • 11
13

In addition to ftft1885's answer

http.get(url, function(res)
{
    var bodyChunks = [];

    res.on('data', function(chunk)
    {
        // Store data chunks in an array
        bodyChunks.push(chunk);
    }).on('error', function(e)
    {
        // Call callback function with the error object which comes from the response
        callback(e, null);
    }).on('end', function()
    {
        // Call callback function with the concatenated chunks parsed as a JSON object (for example)
        callback(null, JSON.parse(Buffer.concat(bodyChunks)));
    });
}).on('error', function(e) {
    // Call callback function with the error object which comes from the request
    callback(e, null);
});

When I had this "socket hang up" error, it was because I wasn't catching the requests errors.

The callback function could be anything; it all depends on the needs of your application. Here's an exemple of a callback logging data with console.log and logging errors with console.error:

function callback(error, data) {
    if (error) {
        console.error('Something went wrong!');
        console.error(error);
    }
    else {
        console.log('All went fine.');
        console.log(data);
    }
}
fwoelffel
  • 412
  • 7
  • 16
  • 2
    What should be in the callback function? Do I define that on the server or is that provided in the response? – jlewkovich Jul 31 '15 at 03:48
  • You should define it on the server – fwoelffel Jul 31 '15 at 09:17
  • What about @jlewkovich's first question? – Daniel Kaplan Oct 20 '21 at 17:27
  • Wouldn't this be cleaner if you did `req.on('error'...` instead? Is there something wrong about that idea? – Daniel Kaplan Oct 20 '21 at 17:35
  • Nothing wrong with this. You can store the [`ClientRequest`](https://nodejs.org/api/http.html#class-httpclientrequest) returned from [`http.get`](https://nodejs.org/api/http.html#httpgetoptions-callback) in a variable (let's say `req`) and add the event listener using the variable instead of chaining: `const req = http.get(...); req.on('error', ...)` – fwoelffel Oct 22 '21 at 07:33
4

use

req.on('error',function(err){})
ftft1885
  • 77
  • 1
  • 2
    answer is a bit short, but to the point: as Eschard1991 points out, you need to handle the error events not only from the response but also from the request object. – scravy Mar 29 '15 at 23:24
0

Most probably your server socket connection was somehow closed before all http.ServerResponse objects have ended. Make sure that you have stopped all incoming requests before doing something with incoming connections (incomming connection is something different than incoming HTTP request).

Mateusz Charytoniuk
  • 1,820
  • 20
  • 31