QuickSnip
← Back to browse

Safe JSON fetch

Fetch JSON with explicit error handling for non-OK responses.

TypeScript7 linesUpdated Jul 17, 2026
Edit
TypeScript
export async function getJSON<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error(`Request failed: ${res.status} ${res.statusText}`);
  }
  return (await res.json()) as T;
}