0
0
Svelteframework~10 mins

Error handling in load in Svelte - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Error handling in load
Page request starts
Call load function
Try to fetch data
Return data
Page renders
End
When a page loads, the load function tries to get data. If it works, data is returned and page shows it. If it fails, error is caught and shown instead.
Execution Sample
Svelte
export async function load() {
  try {
    const res = await fetch('/api/data');
    if (!res.ok) throw new Error('Failed to load');
    return { data: await res.json() };
  } catch (error) {
    return { status: 500, error: new Error('Load error') };
  }
}
This load function fetches data and returns it. If fetching fails, it returns an error to show on the page.
Execution Table
StepActionFetch ResultConditionOutcomeReturned Value
1Call load()N/AN/AStart loadingN/A
2Fetch '/api/data'Response with status 200res.ok is trueSuccess path{ data: ... }
3Page renders with dataN/AN/AShow data on pageN/A
4Call load() againN/AN/AStart loadingN/A
5Fetch '/api/data'Response with status 500res.ok is falseThrow errorError thrown
6Catch errorN/AN/AReturn error info{ status: 500, error: Error('Load error') }
7Page renders errorN/AN/AShow error messageN/A
8EndN/AN/ALoading completeN/A
💡 Execution stops after returning data or error info to render the page accordingly.
Variable Tracker
VariableStartAfter Step 2After Step 5Final
resundefinedResponse 200 OKResponse 500 ErrorN/A
errorundefinedundefinedError('Failed to load') caughtError('Load error') returned
returnedValueundefined{ data: ... }{ status: 500, error: Error('Load error') }N/A
Key Moments - 3 Insights
Why do we check if res.ok is false after fetching?
Because fetch can succeed at network level but the server can respond with an error status. Checking res.ok ensures we catch such errors and handle them properly, as shown in steps 5 and 6.
What happens if an error is thrown inside load?
The error is caught by the catch block (step 6), which returns an error object. This tells SvelteKit to show an error page or message instead of normal data, as seen in step 7.
Why do we return an object with status and error in the catch block?
Returning { status, error } informs SvelteKit about the error status and message. This triggers the framework to render an error page automatically, instead of crashing or showing blank content.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the returned value after a successful fetch at step 2?
A{ data: ... }
B{ status: 500, error: Error('Load error') }
Cundefined
DError thrown
💡 Hint
Check the 'Returned Value' column at step 2 in the execution_table.
At which step does the condition res.ok become false?
AStep 2
BStep 5
CStep 6
DStep 3
💡 Hint
Look at the 'Condition' column in the execution_table where res.ok is checked.
If the fetch URL was changed to a valid endpoint, how would the returnedValue change at step 5?
AIt would throw an error
BIt would return error info
CIt would return { data: ... }
DIt would be undefined
💡 Hint
Refer to variable_tracker and execution_table rows for successful fetch results.
Concept Snapshot
SvelteKit load function fetches data before page shows.
Use try-catch to handle fetch errors.
Check res.ok to detect HTTP errors.
Return { data } on success.
Return { status, error } on failure to show error page.
This keeps user informed and page stable.
Full Transcript
When a SvelteKit page loads, it runs the load function to get data. The load function tries to fetch data from an API. If the fetch is successful and the response is OK, it returns the data. The page then shows this data. If the fetch fails or the response is not OK, the load function catches the error and returns an error object with a status code. This tells SvelteKit to show an error page or message instead of normal content. Checking res.ok is important because fetch can succeed at the network level but the server might respond with an error status. Returning status and error in the catch block helps SvelteKit handle errors gracefully. This way, users see meaningful messages instead of broken pages.