diff --git a/lib/api-request-test.js b/lib/api-request-test.js index 193bc9c..dbbc6f6 100644 --- a/lib/api-request-test.js +++ b/lib/api-request-test.js @@ -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) => { diff --git a/lib/api-request.js b/lib/api-request.js index 07dc20a..4a40f56 100644 --- a/lib/api-request.js +++ b/lib/api-request.js @@ -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')); }