Skip to content

Commit

Permalink
fix: Handle fetch errors with no Response Body
Browse files Browse the repository at this point in the history
When the cozy-stack returns a HTTP error, then a Response Body should
be provided

With current implementation, a null Response Body would produce a
`Cannot read properdy 'message' of null` error as we try to read
`reason.message`

If the Response Body is null then we want cozy-client to throw a
comprehensive error that helps investigate the problem
  • Loading branch information
Ldoppea authored and Crash-- committed Jun 22, 2023
1 parent 22cbe8d commit 890db21
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
34 changes: 34 additions & 0 deletions packages/cozy-stack-client/src/CozyStackClient.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,26 @@ describe('CozyStackClient', () => {
}
})

it('should throw a specific error when the request returns an error with no Response Body', async () => {
fetch.mockResponse(() => {
return Promise.resolve({
headers: {
'content-type': 'application/json; charset=UTF-8'
},
body: JSON.stringify(null),
ok: false,
status: 503,
statusText: '',
type: 'default',
url: 'http://cozy.tools:8080/data/io.cozy.todos'
})
})

await expect(client.fetchJSON('GET', '/foo/bar')).rejects.toThrow(
`FetchError received a 503 error without a Response Body when calling http://cozy.tools:8080/data/io.cozy.todos`
)
})

it('should try to refresh the current token when received an invalid token error', async () => {
const client = new CozyStackClient(FAKE_INIT_OPTIONS)
global.fetch
Expand Down Expand Up @@ -693,6 +713,20 @@ describe('FetchError', () => {
'http://cozy.tools:8080/data/io.cozy.todos'
)
})

it('should throw an error if no reason param is provided', () => {
expect(() => {
new FetchError(
{
url: 'http://cozy.tools:8080/data/io.cozy.todos',
status: 400
},
null
)
}).toThrowError(
`FetchError received a 400 error without a Response Body when calling http://cozy.tools:8080/data/io.cozy.todos`
)
})
})

describe('checkForRevocation', () => {
Expand Down
6 changes: 6 additions & 0 deletions packages/cozy-stack-client/src/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ export class FetchError extends Error {

let wwwAuthenticateErrorMessage = getWwwAuthenticateErrorMessage(response)

if (reason === null) {
throw new Error(
`FetchError received a ${response.status} error without a Response Body when calling ${response.url}`
)
}

Object.defineProperty(this, 'message', {
value:
reason.message ||
Expand Down

0 comments on commit 890db21

Please sign in to comment.