Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS UnhandledException with a HTTPS request

I need some help trying to stop node from throwing this error, or at-least understand why I can't seem to be able to catch it:

events.js:72
    throw er; // Unhandled 'error' event
          ^
Error: socket hang up
at SecurePair.error (tls.js:999:23)
at EncryptedStream.CryptoStream._done (tls.js:695:22)
at CleartextStream.read [as _read] (tls.js:496:24)
at CleartextStream.Readable.read (_stream_readable.js:320:10)
at EncryptedStream.onCryptoStreamFinish (tls.js:301:47)
at EncryptedStream.g (events.js:175:14)
at EncryptedStream.EventEmitter.emit (events.js:117:20)
at finishMaybe (_stream_writable.js:354:12)
at endWritable (_stream_writable.js:361:3)
at EncryptedStream.Writable.end (_stream_writable.js:339:5)
at EncryptedStream.CryptoStream.end (tls.js:633:31)
at Socket.onend (_stream_readable.js:483:10)

This is the code snippet that causes the error:

var req = https.request(options, function(res) {
  res.setEncoding('utf8');
  var buffer = '';
  res.on('data', function(data) {
    buffer += data;
  });
  res.on('end', function() {
    try {
      var json = JSON.parse(buffer);
    } catch (err) {
      return callback(err);
    }
    callback(null, json);
  });
});
req.on('error', function(err) {
  callback(err);
});
req.end(data);

api.prototype._get = function(action, callback, args) {
  args = _.compactObject(args);
  var path = '/api/' + action + '/?' + querystring.stringify(args);
  this._request('get', path, undefined, callback, args)
}

api.prototype._post = function(action, callback, args) {
  var path = '/api/' + action + '/';
  args = _.compactObject(args);
  var data = querystring.stringify(args);
  this._request('post', path, data, callback, args);
}

Why isn't req.on('error' catching this err?

Node version: 0.10.21

like image 502
San1ty Avatar asked Nov 18 '13 13:11

San1ty


1 Answers

You're missing an error-handler for the response.

res.on('error', function errorHandler(err) { console.log(err); });
like image 147
Olli K Avatar answered Oct 05 '22 13:10

Olli K