0 day streak
javascript / beginner
Snippet

Handling Asynchronous API Fetch Requests and Errors in Svelte

Asynchronous JavaScript operations such as HTTP network requests can be encapsulated within `async` functions using `try...catch` blocks. Svelte conditionally renders UI feedback based on whether data was successfully retrieved or caught by error handling logic.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script>
let quote = "";
let errorMessage = "";
async function fetchQuote() {
errorMessage = "";
try {
const response = await fetch("https://api.quotable.io/random");
if (!response.ok) throw new Error("Network response failed");
const data = await response.json();
quote = data.content;
} catch (err) {
errorMessage = err.message;
}
}
</script>
<button on:click={fetchQuote}>Get Quote</button>
{#if errorMessage}
<p class="error">Error: {errorMessage}</p>
{:else if quote}
<blockquote>{quote}</blockquote>
{/if}
svelte
Breakdown
1
async function fetchQuote() {
Declares an asynchronous function that handles Promise-based operations without blocking UI execution.
2
try {
Begins a block of code to test for potential runtime network or parsing errors.
3
const response = await fetch("https://api.quotable.io/random");
Pauses execution until the HTTP fetch request resolves to a Response object.
4
if (!response.ok) throw new Error("Network response failed");
Checks the HTTP response status and throws a custom error if the response indicates failure.
5
const data = await response.json();
Parses the response body text as a JSON object asynchronously.
6
} catch (err) {
Catches any thrown errors and assigns the message to the state variable for user display.