CICCIOSGAMINO / openweather-apis

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

Catching error in getData function in case http.get fails #23

Closed abaretta closed 5 years ago

abaretta commented 6 years ago

Hi,

Thanks for the code! I found that the getData function doesn't catch http.get errors, for instance when OpenWeatherMap is unreachable for whatever reason. To address this I edited the function as outlined below.

Thanks,

Regards, Anne

`function getData(url, callback, tries) {
    options.path = url;
    var DATA = http.get(options, (res) => {
        var chunks = '';
        res.on('data', (chunk) => {
            chunks += chunk;
        });
        res.on('end', () => {
            var parsed = {};

            if (!chunks && (!tries || tries < 3)) {
                return getData(url, callback, (tries || 0) + 1);
            }

            // Try-Catch added by Mikael Aspehed
            try {
                parsed = JSON.parse(chunks)
            } catch (e) {
                parsed = {
                    error: e
                }
            }

            return callback(null, parsed);
        });

        res.on('error', (err) => {
            console.log(`problem with request: ${err.message}`);
        });
    });

    DATA.on('error', (err) => {
        console.log(`problem with request: ${err.message}`);
    });
};`
CICCIOSGAMINO commented 5 years ago

Closed with version 4.0.0