Skip to content

Commit

Permalink
if error response does not contain message set error to Unknown
Browse files Browse the repository at this point in the history
fixes issues addressed here #17
with additional tests
  • Loading branch information
t-o-m- committed Nov 7, 2017
1 parent ac5870c commit 9744258
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
21 changes: 21 additions & 0 deletions lib/api-request-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,27 @@ describe('api', () => {
});
});

describe('when the response status is not 200', () => {
describe('and the response JSON is not formatted correctly', () => {
it('does not blow up', (done) => {
const apiRequest = api.apiRequest(HOST, API_KEY, USER_AGENT);
const METHOD = 'get',
ENDPOINT = '/whoopie-do',
OPTIONS = { endpoint: ENDPOINT },
BAD_JSON_RESPONSE_BODY = { i: 'sorry' };

nock(HOST)[METHOD](ENDPOINT)
.reply(400, BAD_JSON_RESPONSE_BODY);

apiRequest(METHOD, OPTIONS, (err, body) => {
expect(body).toBeUndefined()
expect(err.message).toBe('Unknown error')
done();
});
});
});
});

describe('when the response is not JSON formatted', () => {
describe('and the response status is 200', () => {
it('does not blow up', (done) => {
Expand Down
6 changes: 5 additions & 1 deletion lib/api-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ module.exports = {
} else {
try {
const parsedBody = JSON.parse(body);
cb(new Error(parsedBody.error.message));
if (!parsedBody || !parsedBody.error || !!parsedBody.error.message) {
cb(new Error('Unknown error'));
} else {
cb(new Error(parsedBody.error.message));
}
} catch (e) {
cb(new Error('The response from the server was not a JSON'));
}
Expand Down

0 comments on commit 9744258

Please sign in to comment.