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

Throw error when request returns an HTTP status code greater than 400 #2

Open
carlosvillademor opened this issue Mar 17, 2015 · 1 comment

Comments

@carlosvillademor
Copy link

Hello @mko,

I am using the library to import some data from Runkeeper. I was having some issues where some of the requests where returning 401 or 406 HTTP status code. I think when using request like on:

request(request_details, function(error, response, body) { 
    var parsed;
    try {
        parsed = JSON.parse(body);
    } catch(e) {
        error = new Error('Body reply is not a valid JSON string.');
        error.runkeeperBody = body;
    } finally {
        callback(error, parsed);
    }
});

The response.statusCode and the error should be check before carrying on to do anything with body.

request(request_details, function(error, response, body) { 
    if(error || response.statusCode !=== 200) {
        return callback(error || 'Status code' + response.statusCode);
    }
    var parsed;
    try {
        parsed = JSON.parse(body);
    } catch(e) {
    error = new Error('Body reply is not a valid JSON string.');
        error.runkeeperBody = body;
    } finally {
        callback(error, parsed);
    }
});

If there is an error or the status code of the response is not 200, we execute the callback with the error. I'll get a pull request for you to merge if you agree this change needs to be integrated.

I was getting an undefined access_token because of the same issue on:

request(request_details, function(error, response, body) {
    callback(error, JSON.parse(body)['access_token']);
});

The response status code was 401 or 406, the callback was called with no error and an undefined body.

@mko
Copy link
Owner

mko commented Mar 17, 2015

Thanks for finding this. I've not been actively working with the library recently, but it makes sense to add these checks. Submit the PR, and I'll move forward with a new release on NPM later this week.

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