How to Handle Errors in Fetch Requests in Svelte
In Svelte, handle errors in
fetch by wrapping the call in a try/catch block or checking the response status before processing data. Use reactive variables to show error messages in the UI when a fetch fails.Why This Happens
When you use fetch without checking for errors, your app may try to use data that isn't there or ignore network problems. This causes your app to crash or behave unexpectedly.
svelte
let data; fetch('https://api.example.com/data') .then(response => response.json()) .then(json => { data = json; });
Output
If the fetch fails or the server returns an error status, the app does not handle it and may crash or show nothing.
The Fix
Use async/await with try/catch to catch errors. Also check if the response is OK before reading data. Show an error message if something goes wrong.
svelte
<script> import { onMount } from 'svelte'; let data = null; let error = null; onMount(async () => { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error(`Error: ${response.status} ${response.statusText}`); } data = await response.json(); } catch (err) { error = err.message; } }); </script> {#if error} <p style="color: red;">{error}</p> {:else if data} <pre>{JSON.stringify(data, null, 2)}</pre> {:else} <p>Loading...</p> {/if}
Output
Shows the fetched data if successful, or a red error message if fetch fails or server returns error.
Prevention
Always handle fetch errors by using try/catch or .catch(). Check response.ok before processing data. Use reactive variables to update UI with error states. Consider using Svelte stores for shared error handling.
Related Errors
- TypeError: Failed to fetch - Happens when network is down or URL is wrong; check URL and internet connection.
- Unexpected token in JSON - Occurs if response is not valid JSON; verify API response format.
- Unhandled promise rejection - Happens if fetch errors are not caught; always use
try/catchor.catch().
Key Takeaways
Always wrap fetch calls in try/catch to handle errors gracefully.
Check response.ok before parsing JSON to catch HTTP errors.
Use reactive variables to show error messages in the UI.
Handle network and parsing errors separately for clearer debugging.
Test your fetch calls with offline mode or wrong URLs to ensure error handling works.