Skip to content

Commit

Permalink
chore(migration): add better error message when request fails (#5567)
Browse files Browse the repository at this point in the history
* chore(migration): add better error message when request fails

* fix(migration): add error message if json parsing fails
  • Loading branch information
binoy14 authored and bjoerge committed Jan 30, 2024
1 parent 458ac49 commit f1c2cd4
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions packages/@sanity/migrate/src/fetch-utils/fetchStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,25 @@ export interface HTTPError extends Error {
statusCode: number
}

export function assert2xx(res: Response) {
export async function assert2xx(res: Response): Promise<void> {
if (res.status < 200 || res.status > 299) {
const err = new Error(`HTTP Error ${res.status}: ${res.statusText}`) as HTTPError
const response = await res.json().catch(() => {
throw new Error(`Error parsing JSON ${res.status}: ${res.statusText}`)
})

const message = response.error
? response.error.description
: `HTTP Error ${res.status}: ${res.statusText}`

const err = new Error(message) as HTTPError
err.statusCode = res.status
throw err
}
}

export async function fetchAsyncIterator({url, init}: FetchOptions) {
const response = await fetch(url, init)
assert2xx(response)
await assert2xx(response)
if (response.body === null) throw new Error('No response received')
return streamAsyncIterator(response.body)
}

0 comments on commit f1c2cd4

Please sign in to comment.