CICCIOSGAMINO / openweather-apis

Simple APIs for OpenWeatherMap.org basic services
GNU General Public License v3.0
44 stars 27 forks source link

Unexpected token #1

Closed dagalufh closed 8 years ago

dagalufh commented 9 years ago

Hi

I have a node.js script that uses your plugin but i once in a while get the below error:

The calling code looks like this: weather.getAllWeather(function(err, JSONObj){ variables.weather = JSONObj; });

And the error i receive is: undefined:1 failed to connect ^ SyntaxError: Unexpected token i at Object.parse (native) at IncomingMessage. (E:\Temp\Node.js\Nodejs - 150421-1541\node_mo dules\openweather-apis\index.js:163:38) at IncomingMessage.emit (events.js:107:17) at IncomingMessage.Readable.read (_stream_readable.js:373:10) at flow (_streamreadable.js:750:26) at resume (_stream_readable.js:730:3) at _stream_readable.js:717:7 at process._tickCallback (node.js:355:11)

The problem is that it's halting the code completly. I've tried checking for (err) but it halts before that since it's in the index.js of Openweather-apis that the error occurs. Any idea on how i can avoid this?

Perhaps a implementation of checking if there is a valid JSON object being returned before calling the callback on your index.js:163?

dagalufh commented 9 years ago

Hi again

This is my fix for the issue:

function getData(callback){ options.path = buildPath(); var req = http.get(options, function(res){ //console.log(res); res.setEncoding('utf-8'); res.on('data', function (chunk) { var parsed = {};

      // Try-Catch added by Mikael Aspehed
      try {
          parsed = JSON.parse(chunk)
      } catch (e) {
          parsed = {error:'error'};
      }
      return callback(null, parsed);
  });

  res.on('error', function(err){
      return callback(err, null);
  })
});

}

Then i just in the calling code checks if the returning object contains a error property or not. That way i can continue without halting it just because Openweathermap is busy.

CICCIOSGAMINO commented 9 years ago

I'll fix soon ! Thanks for the Advice !!

CICCIOSGAMINO commented 8 years ago

Thanks ! Closed