javascript / beginner
Snippet
Handling Async Errors with Await Catch Blocks
Svelte allows direct handling of Promise rejections inside the markup using the {:catch error} block. This ensures that runtime network or parsing exceptions are gracefully presented to the user without crashing the component.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script>async function fetchUserProfile(userId) {const res = await fetch(`/api/users/${userId}`);if (!res.ok) {throw new Error(`Failed to load profile (Status: ${res.status})`);}return res.json();}let userPromise = fetchUserProfile(42);</script>{#await userPromise}<p>Loading profile...</p>{:then user}<h2>{user.name}</h2>{:catch error}<p class="error">Error: {error.message}</p>{/await}
svelte
Breakdown
1
throw new Error(`Failed to load profile (Status: ${res.status})`);
Creates and throws a descriptive Error object when the HTTP response status is not successful.
2
{:catch error}
Svelte block that catches rejected promises and binds the thrown error object for display in the template.