Skip to content

Commit

Permalink
Fix: ignore failed json parse (#189)
Browse files Browse the repository at this point in the history
* Fix: ignore failed json parse

* Prettier
  • Loading branch information
katspaugh committed Jul 16, 2024
1 parent a7d2769 commit 9f85795
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
11 changes: 5 additions & 6 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,15 @@ async function parseResponse<T>(resp: Response): Promise<T> {
let json

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

if (!resp.ok) {
const errTxt = isErrorResponse(json) ? `${json.code}: ${json.message}` : resp.statusText
const errTxt = isErrorResponse(json)
? `CGW error - ${json.code}: ${json.message}`
: `CGW error - status ${resp.statusText}`
throw new Error(errTxt)
}

Expand Down
7 changes: 4 additions & 3 deletions tests/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,18 +198,19 @@ describe('utils', () => {
})
})

it('should not throw for a 204 response', async () => {
const jsonMock = jest.fn()
it('should not throw for an non-JSON response', async () => {
const jsonMock = jest.fn().mockRejectedValue('error')

fetchMock.mockImplementation(() => {
return Promise.resolve({
ok: true,
status: 204,
statusText: 'No Content',
json: jsonMock,
})
})

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

expect(fetch).toHaveBeenCalledWith('/test/safe', {
method: 'DELETE',
Expand Down

0 comments on commit 9f85795

Please sign in to comment.