0
0
Svelteframework~5 mins

Error handling in load in Svelte

Choose your learning style9 modes available
Introduction

Error handling in load helps your app manage problems when fetching data or preparing a page. It keeps your app friendly and avoids crashes.

When fetching data from an API that might fail
When loading page data that depends on external sources
When you want to show a friendly message if something goes wrong
When you want to redirect users if loading fails
When you want to log errors for debugging
Syntax
Svelte
export async function load({ fetch, params }) {
  try {
    const response = await fetch('/api/data');
    if (!response.ok) {
      throw new Error('Failed to fetch data');
    }
    const data = await response.json();
    return { data };
  } catch (error) {
    return { status: 500, error: new Error('Could not load data') };
  }
}

The load function runs before the page shows.

Use try...catch to catch errors and return a status and error message.

Examples
This example fetches items and returns a 404 error if it fails.
Svelte
export async function load({ fetch }) {
  try {
    const res = await fetch('/api/items');
    if (!res.ok) throw new Error('Network error');
    const items = await res.json();
    return { items };
  } catch {
    return { status: 404, error: new Error('Items not found') };
  }
}
No error handling needed here because no data is fetched.
Svelte
export async function load() {
  return { message: 'Hello!' };
}
Error is handled by checking response status without try/catch.
Svelte
export async function load({ fetch }) {
  const response = await fetch('/api/data');
  if (!response.ok) {
    return { status: 500, error: new Error('Server error') };
  }
  const data = await response.json();
  return { data };
}
Sample Program

This Svelte page tries to load user data before showing. If loading fails, it shows a friendly message.

Svelte
<script context="module">
  export async function load({ fetch }) {
    try {
      const res = await fetch('/api/user');
      if (!res.ok) {
        throw new Error('User data not found');
      }
      const user = await res.json();
      return { user };
    } catch (error) {
      return { user: null };
    }
  }
</script>

<script>
  export let data;
</script>

<main>
  {#if data.user}
    <h1>Welcome, {data.user.name}!</h1>
  {:else}
    <p>Loading user data failed.</p>
  {/if}
</main>
OutputSuccess
Important Notes

To trigger SvelteKit's error page, return an object with status and error.

Use try...catch to handle unexpected errors gracefully.

Test your error handling by simulating failed fetch calls in the browser DevTools Network tab.

Summary

Error handling in load keeps your app stable when data fails to load.

Use try...catch and check response status to catch problems.

Return { status, error } to show error pages or messages.