From f1c2cd45a46357f2606056d35fa4d153c1a0eb4e Mon Sep 17 00:00:00 2001 From: Binoy Patel Date: Fri, 26 Jan 2024 13:25:13 -0500 Subject: [PATCH] chore(migration): add better error message when request fails (#5567) * chore(migration): add better error message when request fails * fix(migration): add error message if json parsing fails --- .../@sanity/migrate/src/fetch-utils/fetchStream.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/packages/@sanity/migrate/src/fetch-utils/fetchStream.ts b/packages/@sanity/migrate/src/fetch-utils/fetchStream.ts index 8e07dfcd72e..e4497d5b874 100644 --- a/packages/@sanity/migrate/src/fetch-utils/fetchStream.ts +++ b/packages/@sanity/migrate/src/fetch-utils/fetchStream.ts @@ -8,9 +8,17 @@ export interface HTTPError extends Error { statusCode: number } -export function assert2xx(res: Response) { +export async function assert2xx(res: Response): Promise { 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 } @@ -18,7 +26,7 @@ export function assert2xx(res: Response) { 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) }