philschatz / octokat.js

:octocat: Github API Client using Promises or callbacks. Intended for the browser or NodeJS.
http://philschatz.com/2014/05/25/octokat/
MIT License
421 stars 133 forks source link

Invalid Error Response #282

Open aklgupta opened 5 years ago

aklgupta commented 5 years ago

I am using octokat v0.10.0, While trying to handle bad login request, I noticed that the response in case of an error is invalid. I was unable to use it as a JSON. The object type is object, however, the object has no keys. Parsing it using JSON.parse thrown error as well.

The response I receive is as follows:

Error: {
  "message": "Bad credentials",
  "documentation_url": "https://developer.github.com/v3"
}
 GET https://api.github.com/repos/f/f Status: 401
    at eval (requester.js:225)

Here's my code snippet

console.log(username);
console.log(password);
console.log(reponame);

var octo = new Octokat({
    username: username,
    password: password,
});
var repo = octo.repos(username, reponame);

repo.fetch()
.then((info) => {
    // do work
})
.catch((err) => {
    console.log("error");
    console.log(err);
    console.log(typeof(err));
    console.log(err.message);
    console.log(typeof(err.message));
    // JSON.parse(err);
    JSON.parse(err.message);
    this.status = 'failure';
});

Output of the above code is:

user  // Changed intentionally
pass  // Changed intentionally
repo  // Changed intentionally

GET https://api.github.com/repos/f/f 401 (Unauthorized)

error

Error: {
  "message": "Bad credentials",
  "documentation_url": "https://developer.github.com/v3"
}
 GET https://api.github.com/repos/f/f Status: 401
    at eval (requester.js:225)

object

{
  "message": "Bad credentials",
  "documentation_url": "https://developer.github.com/v3"
}
 GET https://api.github.com/repos/f/f Status: 401

string

index.js:97 Uncaught (in promise) SyntaxError: Unexpected token G in JSON at position 0
    at JSON.parse (<anonymous>)
    at eval (index.js:97)

How do I parse this error response? Even octo.parse was not helpful