Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
abaretta opened this issue Dec 19, 2017 · 1 comment
Closed

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

abaretta opened this issue Dec 19, 2017 · 1 comment

Comments

@abaretta
Copy link

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
Copy link
Owner

Closed with version 4.0.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants