javascript / expert
Snippet
Isomorphic Fetching Wrapper with Error Handling
An isomorphic fetch wrapper ensures consistent error handling across both server-side load functions and client-side interactions. Passing the fetcher as an argument maintains compatibility with SvelteKit's specialized fetch implementation.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
export async function apiFetch(url, fetcher = fetch) {try {const response = await fetcher(url);if (!response.ok) {throw new Error(`HTTP Error: ${response.status}`);}return await response.json();} catch (err) {console.error('Fetch failed:', err);return { error: true, message: err.message };}}
svelte
Breakdown
1
fetcher = fetch
Defaults to the global fetch, but allows injecting SvelteKit's fetch for server-side relative URL support.
2
if (!response.ok)
Explicitly checks for non-2xx status codes which do not trigger the catch block in the native Fetch API.
3
return { error: true, ... }
Returns a predictable object structure to prevent UI crashes in the calling component.