diff --git a/lib/wrapper.js b/lib/wrapper.js index d9f56c8..4438783 100644 --- a/lib/wrapper.js +++ b/lib/wrapper.js @@ -96,7 +96,7 @@ class RequestWrapper { throw new SuiteRequestError( 'Error in http response (status: ' + response.statusCode + ')', response.statusCode, - response.body + this._parseBody(response) ); } @@ -105,13 +105,19 @@ class RequestWrapper { throw new SuiteRequestError('Empty http response', 500, response.statusMessage); } - if (this._isJsonResponse(response)) { - try { - response.body = JSON.parse(response.body); - } catch (ex) { - logger.error('fatal_error', ex, this._getLogParameters()); - throw new SuiteRequestError(ex.message, 500); - } + response.body = this._parseBody(response); + } + + _parseBody(response) { + if (!this._isJsonResponse(response)) { + return response.body; + } + + try { + return JSON.parse(response.body); + } catch (ex) { + logger.error('fatal_error', ex, this._getLogParameters()); + throw new SuiteRequestError(ex.message, 500); } } } diff --git a/lib/wrapper.spec.js b/lib/wrapper.spec.js index a3c7a32..495dc4b 100644 --- a/lib/wrapper.spec.js +++ b/lib/wrapper.spec.js @@ -70,6 +70,7 @@ describe('Wrapper', function() { expect(err).to.be.an.instanceof(SuiteRequestError); expect(err.message).to.eql('Error in http response (status: 400)'); expect(err.code).to.eql(400); + expect(err.data).to.eql({ replyText: 'Unknown route' }); expect(requestGetStub).to.be.calledWith(expectedRequestOptions); } }); @@ -135,6 +136,22 @@ describe('Wrapper', function() { } throw new Error('Error should have been thrown'); }); + + it('should throw a http response error even if the response body is empty', function *() { + apiResponse.body = '404 Not Found'; + apiResponse.statusCode = 404; + apiResponse.headers = { 'content-type': 'text/plain' }; + + try { + yield wrapper.send(); + throw new Error('should throw'); + } catch (err) { + expect(err).to.be.an.instanceOf(SuiteRequestError); + expect(err.code).to.eql(apiResponse.statusCode); + expect(err.message).to.eql('Error in http response (status: 404)'); + expect(err.data).to.eql(apiResponse.body); + } + }); });