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

@vercel/blob - Return more useful error message when retrieveClientToken throws custom error message #489

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
14 changes: 12 additions & 2 deletions packages/blob/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 {
Expand All @@ -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;
}
Expand Down