Performance: Error handling in HTTP calls
This affects the responsiveness and smoothness of the user interface during and after HTTP requests.
import { ref } from 'vue'; const data = ref(null); const error = ref(null); async function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) throw new Error('Network response was not ok'); data.value = await response.json(); error.value = null; } catch (err) { error.value = err.message; } }
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { this.data = data; }) .catch(error => { alert('Error occurred: ' + error.message); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking alert() in catch | Minimal DOM changes | Triggers reflow after alert dismissed | Blocks paint during alert | [X] Bad |
| Reactive error state update | Updates reactive DOM nodes | Single reflow for error message | Smooth paint without blocking | [OK] Good |
try...catch blocks in Vue HTTP calls?try...catchtry...catch block is used to catch errors that happen during code execution, such as network failures or exceptions.try...catch helps catch these errors and handle them gracefully.response.ok property is a boolean that is true if the HTTP status code is in the 200-299 range, indicating success.response.ok, which is the recommended and clearer way. Options C and D are not valid properties.fetchData() return if the server responds with status 404?response.ok. For status 404, response.ok is false, so it throws an error.catch block, which returns the string 'Fetch failed'.async function getUser() {
try {
const response = await fetch('/user');
if (response.ok) {
const user = response.json();
return user;
}
} catch (e) {
console.error(e);
}
}response.json() method returns a Promise, so it must be awaited to get the actual data.response.json() without await, so it returns a Promise instead of user data.try...catch allows catching errors. Setting an error message in Vue state lets the UI update to inform the user.aria-live="polite" on the error message container ensures screen readers announce the message politely, improving accessibility.aria-live="polite" for screen readers [OK]Pass the test and this pattern moves unknown