How do you handle errors in async/await?
With async/await, you handle errors using familiar try/catch instead of .catch().
try/catch — wrap awaited calls; rejected promises throw into the catch block.
finally — run cleanup whether it succeeded or failed.
Multiple awaits — one try/catch can cover several, or wrap individually for granular handling.
For parallel calls: Promise.all rejects on the first failure — use Promise.allSettled to get every result.
// Basic try/catch
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (err) {
console.error('Failed to fetch user:', err.message);
throw err; // Re-throw for caller to handle
}
}
// Multiple operations
async function loadDashboard(userId) {
try {
const user = await fetchUser(userId);
const [orders, notifications] = await Promise.all([
fetchOrders(userId),
fetchNotifications(userId)
]);
return { user, orders, notifications };
} catch (err) {
return { error: err.message };
}
}
// Go-style wrapper (no try/catch)
function to(promise) {
return promise
.then(data => [null, data])
.catch(err => [err, null]);
}
async function loadData() {
const [err, user] = await to(fetchUser(1));
if (err) return handleError(err);
const [err2, orders] = await to(fetchOrders(user.id));
if (err2) return handleError(err2);
return { user, orders };
}
// Per-promise catch
const user = await fetchUser(1).catch(err => null); // Returns null on errortry/catch wraps async operations — rejected promises throw inside the catch. Re-throwing (throw err) propagates errors to callers.
The Go-style to() wrapper returns [error, data] tuples, avoiding try/catch nesting. Per-promise .catch provides inline error handling with fallback values.
Show try/catch (standard), the Go-style tuple wrapper (advanced), and per-promise .catch (inline fallback). Know that unhandled rejections in async functions crash the process in Node.js.
Always handle or propagate errors — never silently swallow them.