Performance: Error handling in load
This affects page load speed and user experience by controlling how errors during data fetching impact rendering and interactivity.
export async function load({ fetch }) { try { const res = await fetch('/api/data'); if (!res.ok) { return { data: null, error: 'Failed to load data' }; } const data = await res.json(); return { data }; } catch (e) { return { data: null, error: 'Network error' }; } }
export async function load({ fetch }) { const res = await fetch('/api/data'); if (!res.ok) { throw new Error('Failed to load data'); } const data = await res.json(); return { data }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Throw error without fallback | Minimal DOM nodes but blocks rendering | 0 reflows but blocks layout | Delays paint until error handled | [X] Bad |
| Catch error and return fallback data | Adds error message nodes | 1 reflow for error UI | Paints fallback UI quickly | [OK] Good |
load function in SvelteKit?load in SvelteKitload function fetches data before the page renders.load function?error function to throw HTTP errors with status and message.throw error(404, 'Not found'). Other options are invalid or incomplete.load function, what will be the output if the fetch fails with a 500 status?
export async function load() {
try {
const res = await fetch('/api/data');
if (!res.ok) {
throw error(res.status, 'Failed to load data');
}
const data = await res.json();
return { data };
} catch (err) {
return { status: err.status || 500, error: err.message };
}
}res.ok is false, so throw error(500, 'Failed to load data') runs.status and error from the error.load function that causes the error handling to fail:
export async function load() {
try {
const res = await fetch('/api/data');
if (!res.ok) {
return error(res.status, 'Failed to load');
}
const data = await res.json();
return { data };
} catch (err) {
return { status: err.status, error: err.message };
}
}return error(...) which does not throw an error but returns a value, so error handling is bypassed.throw error(...) so the catch block or error page activates.load. Which approach correctly handles this and passes the error to the page?loaderror(403, 'Access denied') inside load tells SvelteKit to show the error page.error.svelte to customize error displayerror.svelte page lets you show custom messages based on the error status and message.Pass the test and this pattern moves unknown