0 day streak
javascript / expert
Snippet

Defensive Async UI with Catch Blocks

Svelte's #await block provides a native way to handle asynchronous data flows directly in the template. Using the catch branch ensures that runtime errors (like network failures) are handled gracefully without crashing the UI.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
{#await fetchUserData(id)}
<p>Loading profile...</p>
{:then user}
<h1>{user.name}</h1>
{:catch error}
<div class="error-banner">
<p>Could not load user: {error.message}</p>
<button onclick={retry}>Retry</button>
</div>
{/await}
svelte
Breakdown
1
{#await fetchUserData(id)}
Initiates the promise and displays the initial pending state.
2
{:then user}
Executes when the promise resolves, providing access to the returned data.
3
{:catch error}
Captures any rejection or error thrown during the fetch process for fallback UI.