Use try/catch with async/await for error handling
async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
}async function robustFetch(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return { success: true, data };
} catch (error) {
if (error.name === 'TypeError') {
console.error('Network error:', error);
} else {
console.error('Error:', error.message);
}
return { success: false, error: error.message };
}
}
// Usage
const result = await robustFetch('https://api.example.com/data');
if (result.success) {
console.log(result.data);
}try {
await operation();
} catch (error) {
handleError(error);
} finally {
cleanup(); // Always runs
}fetch(url)
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.error(error));Avoid unhandled promise rejections
// DON'T DO THIS
async function getData() {
const data = await fetch(url); // No error handling!
return data;
}✓ Works in all modern browsers (ES2017+)