0 day streak
javascript / beginner
Snippet

Managing Asynchronous Request Failures with Try Catch in Svelte

Wrapping asynchronous operations in a `try...catch` block intercepts network and parsing exceptions, allowing the UI state to update cleanly with user-friendly feedback.

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
24
25
26
27
<script>
let status = 'idle';
let errorMessage = '';
async function sendReport() {
status = 'submitting';
errorMessage = '';
try {
const response = await fetch('/api/report', { method: 'POST' });
if (!response.ok) {
throw new Error('Server returned an error status code');
}
status = 'success';
} catch (err) {
status = 'error';
errorMessage = err.message;
}
}
</script>
<button on:click={sendReport} disabled={status === 'submitting'}>
Submit Report
</button>
{#if status === 'error'}
<p class="error">Error: {errorMessage}</p>
{/if}
svelte
Breakdown
1
try {
Starts the block of code monitored for runtime errors and failed operations.
2
throw new Error('Server returned an error status code');
Manually throws an Error instance if the HTTP status indicates failure.
3
} catch (err) {
Catches any thrown exception during the fetch workflow.
4
errorMessage = err.message;
Extracts the readable message string from the error to display in the markup.