Skip to content

Commit 9f85795

Browse files
authored
Fix: ignore failed json parse (#189)
* Fix: ignore failed json parse * Prettier
1 parent a7d2769 commit 9f85795

File tree

2 files changed

+9
-9
lines changed

2 files changed

+9
-9
lines changed

src/utils.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,16 +41,15 @@ async function parseResponse<T>(resp: Response): Promise<T> {
4141
let json
4242

4343
try {
44-
// An HTTP 204 - No Content response doesn't contain a body so trying to call .json() on it would throw
45-
json = resp.status === 204 ? {} : await resp.json()
44+
json = await resp.json()
4645
} catch {
47-
if (resp.headers && resp.headers.get('content-length') !== '0') {
48-
throw new Error(`Invalid response content: ${resp.statusText}`)
49-
}
46+
json = {}
5047
}
5148

5249
if (!resp.ok) {
53-
const errTxt = isErrorResponse(json) ? `${json.code}: ${json.message}` : resp.statusText
50+
const errTxt = isErrorResponse(json)
51+
? `CGW error - ${json.code}: ${json.message}`
52+
: `CGW error - status ${resp.statusText}`
5453
throw new Error(errTxt)
5554
}
5655

tests/utils.test.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -198,18 +198,19 @@ describe('utils', () => {
198198
})
199199
})
200200

201-
it('should not throw for a 204 response', async () => {
202-
const jsonMock = jest.fn()
201+
it('should not throw for an non-JSON response', async () => {
202+
const jsonMock = jest.fn().mockRejectedValue('error')
203+
203204
fetchMock.mockImplementation(() => {
204205
return Promise.resolve({
205206
ok: true,
206207
status: 204,
208+
statusText: 'No Content',
207209
json: jsonMock,
208210
})
209211
})
210212

211213
await expect(fetchData('/test/safe', 'DELETE')).resolves.toEqual({})
212-
expect(jsonMock).not.toHaveBeenCalled()
213214

214215
expect(fetch).toHaveBeenCalledWith('/test/safe', {
215216
method: 'DELETE',

0 commit comments

Comments
 (0)