diff --git a/packages/blob/src/client.ts b/packages/blob/src/client.ts index f9d4f84f4..74d103f7c 100644 --- a/packages/blob/src/client.ts +++ b/packages/blob/src/client.ts @@ -4,7 +4,7 @@ import type { IncomingMessage } from 'node:http'; // When bundled via a bundler supporting the `browser` field, then // the `undici` module will be replaced with https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API // for browser contexts. See ./undici-browser.js and ./package.json -import { fetch } from 'undici'; +import { fetch, type Response } from 'undici'; import type { BlobCommandOptions } from './helpers'; import { BlobError, getTokenFromOptionsOrEnv } from './helpers'; import { createPutMethod } from './put'; @@ -334,7 +334,8 @@ async function retrieveClientToken(options: { }); if (!res.ok) { - throw new BlobError('Failed to retrieve the client token'); + const errorMessage = await tryGetErrorMessageFromResponse(res); + throw new BlobError(errorMessage ?? 'Failed to retrieve the client token'); } try { @@ -345,6 +346,15 @@ async function retrieveClientToken(options: { } } +async function tryGetErrorMessageFromResponse(res: Response) { + const jsonBody = await res.json().catch(() => null); + if (!jsonBody) return; + if (typeof jsonBody !== 'object') return; + if ('error' in jsonBody && typeof jsonBody.error === 'string') { + return jsonBody.error; + } +} + function toAbsoluteUrl(url: string): string { return new URL(url, window.location.href).href; }