0 day streak
javascript / beginner
Snippet

Asynchronous Fetch Error Handling in Setup

Using try/catch inside async functions ensures network failures or bad HTTP response statuses are captured gracefully and reflected in reactive error states instead of breaking the script execution.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { ref } from 'vue';
const user = ref(null);
const errorMessage = ref(null);
async function loadUserData(userId) {
try {
errorMessage.value = null;
const res = await fetch(`/api/user/${userId}`);
if (!res.ok) {
throw new Error('Network response failed');
}
user.value = await res.json();
} catch (err) {
errorMessage.value = err.message;
}
}
vue
Breakdown
1
try {
Begins a guarded block to monitor asynchronous operations for runtime exceptions.
2
if (!res.ok) { throw new Error('Network response failed'); }
Manually triggers an error when the server returns an unsuccessful HTTP status code.
3
user.value = await res.json();
Parses JSON payload on success and assigns it to the reactive user reference.
4
} catch (err) { errorMessage.value = err.message; }
Handles any caught errors by saving the error description into reactive state.