Skip to content
This repository has been archived by the owner on Nov 28, 2022. It is now read-only.

Commit

Permalink
Add error handling around await response.json() call
Browse files Browse the repository at this point in the history
This is to catch cases where they return `content-type: application/json` but do not return valid JSON

We have to clone the object first before we parse, as the objects can only be read once
  • Loading branch information
Dom Harrington committed Aug 3, 2018
1 parent d5d890a commit 4cbb84e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
10 changes: 10 additions & 0 deletions packages/api-explorer/__tests__/lib/parse-response.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,13 @@ test('should parse non-json response as text', async () => {
nonJsonResponseBody,
);
});

test('should not error if invalid json is returned', async () => {
const invalidJsonResponse = new Response('plain text', {
headers: {
'Content-Type': 'application/json',
},
});

expect((await codeSampleResponse(har, invalidJsonResponse)).responseBody).toEqual('plain text');
});
14 changes: 13 additions & 1 deletion packages/api-explorer/src/lib/parse-response.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ async function parseResponse(har, response) {
const querystring =
Object.keys(convertedQueryString).length > 0 ? `?${stringify(convertedQueryString)}` : '';

let responseBody;
// We have to clone it before reading, just incase
// we cannot parse it as JSON later, then we can
// re-read again as plain text
const clonedResponse = response.clone();

try {
responseBody = await response[isJson ? 'json' : 'text']();
} catch (e) {
responseBody = await clonedResponse.text();
}

return {
method: har.log.entries[0].request.method,
requestHeaders: har.log.entries[0].request.headers.map(
Expand All @@ -24,7 +36,7 @@ async function parseResponse(har, response) {
isBinary: !!(contentDisposition && contentDisposition.match(/attachment/)),
url: har.log.entries[0].request.url.replace('https://try.readme.io/', '') + querystring,
status: response.status,
responseBody: await response[isJson ? 'json' : 'text'](),
responseBody,
};
}

Expand Down

0 comments on commit 4cbb84e

Please sign in to comment.