Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: ignore failed json parse #189

Merged
merged 2 commits into from
Jul 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading