0

I'm getting a error of socket end, I'm trying to do a http request (getPrologFarm2) to get info from prolog and it's giving me this error, I already did one before just like this and it did work.

Error:

Exception has occurred: Error
Error: socket hang up
    at createHangUpError (_http_client.js:254:15)
    at Socket.socketOnEnd (_http_client.js:346: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._tickCallback (internal/process/next_tick.js:104:9)

Code:

router.route('/farmacias')
  .get(function (req, res) {
    var info;

    client.methods.getFarmacias(function (data, res) {
      info = data;
    });

    sleep(2000);

    var hours = new Date().getHours();
    var list = [];

    for (var i = 1; i < info.length; i++) {
      if (hours < 12) {
        if (info[i].restricaoTemporal == 'manha') {
          list.push(info[i].nome);
        }
      } else {
        if (info[i].restricaoTemporal == 'tarde') {
          list.push(info[i].nome);
        }
      }
    }

    var info1;

    client.methods.getPrologFarm2(function (data, res) {
      info1 = data
    });

    res.json(info1);

  });

1 Answers1

0

You are getting an error because you code inside .get(function (req, res) throws an unhandled exception and the socket crashes.

As mentioned by @Jeremy Thille in the comments you have some Asynchronous calls and sleep is not the answer to that. Maybe thats the issue because info1 would be undefined when you try to convert it into json.

First you should try to add a try/catch block at the whole get function to check what the error is, like this

router.route('/farmacias')
  .get(function(req, res) {

    try {
      //your code

    } catch (e) {
      res.send(e)
    }

  });

Secondly, since you are not using Promises and have callback your code should look more like this.

    router.route('/farmacias')
      .get(function(req, res) {
        client.methods.getPrologFarm2(function(data, res) {
          res.json(data);
        });
      });

or like this

router.route('/farmacias')
  .get(function(req, res) {
    client.methods.getFarmacias(function(data, res) {

      var hours = new Date().getHours();
      var list = [];

      for (var i = 1; i < data.length; i++) {
        if (hours < 12) {
          if (data[i].restricaoTemporal == 'manha') {
            list.push(data[i].nome);
          }
        } else {
          if (data[i].restricaoTemporal == 'tarde') {
            list.push(data[i].nome);
          }
        }
      }

      res.json(list);

    });

  });
Stamos
  • 3,938
  • 1
  • 22
  • 48