wrap JSON.parse's SynaxError with FetchError

This commit is contained in:
jared kantrowitz 2017-06-19 19:19:06 -04:00 committed by Jared Kantrowitz
parent 553d50e804
commit 1804041726
2 changed files with 23 additions and 2 deletions

View File

@ -87,7 +87,14 @@ Body.prototype = {
* @return Promise
*/
json() {
return consumeBody.call(this).then(buffer => JSON.parse(buffer.toString()));
return consumeBody.call(this).then((buffer) => {
return JSON.parse(buffer.toString());
}).catch((err) => {
if (err instanceof SyntaxError) {
return Body.Promise.reject(new FetchError(`invalid json response body at ${this.url} reason: ${err.message}`, 'invalid-json'));
}
throw err;
})
},
/**

View File

@ -446,7 +446,9 @@ describe('node-fetch', () => {
url = `${base}error/json`;
return fetch(url).then(res => {
expect(res.headers.get('content-type')).to.equal('application/json');
return expect(res.json()).to.eventually.be.rejectedWith(Error);
return expect(res.json()).to.eventually.be.rejected
.and.be.an.instanceOf(FetchError)
.and.include({ type: 'invalid-json' });
});
});
@ -463,6 +465,18 @@ describe('node-fetch', () => {
});
});
it('should reject when trying to parse no content response as json', function() {
url = `${base}no-content`;
return fetch(url).then(res => {
expect(res.status).to.equal(204);
expect(res.statusText).to.equal('No Content');
expect(res.ok).to.be.true;
return expect(res.json()).to.eventually.be.rejected
.and.be.an.instanceOf(FetchError)
.and.include({ type: 'invalid-json' });
});
});
it('should handle no content response with gzip encoding', function() {
url = `${base}no-content/gzip`;
return fetch(url).then(res => {