Interview question
How do you handle errors with async/await? async/await के साथ errors कैसे handle करें?
Answer
Errors in async/await are handled with standard try/catch blocks, unlike Promise chains which use .catch(). A rejected awaited Promise throws inside the try block.
async function fetchData() {
try {
const response = await fetch('/api/data');
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.log('Something went wrong:', error.message);
return null; // fallback value
} finally {
console.log('Fetch attempt finished'); // always runs
}
}
// Handling errors from multiple awaits individually
async function processOrder(orderId) {
let order;
try {
order = await getOrder(orderId);
} catch (error) {
console.log('Could not fetch order:', error.message);
return;
}
try {
await processPayment(order);
} catch (error) {
console.log('Payment failed:', error.message);
await refundIfNeeded(order);
}
}
// Common mistake: forgetting try/catch causes unhandled rejection
async function risky() {
const data = await fetch('/might-fail'); // if this rejects, function throws silently
return data;
}
risky().catch(err => console.log('Caught outside:', err)); // still catchable via .catch() on the callasync/await में errors standard try/catch blocks से handle होते हैं, Promise chains की तरह .catch() से नहीं। Rejected awaited Promise try block के अंदर throw करता है।
async function fetchData() {
try {
const response = await fetch('/api/data');
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.log('कुछ गलत हुआ:', error.message);
return null;
} finally {
console.log('Fetch attempt finished');
}
}
async function processOrder(orderId) {
let order;
try {
order = await getOrder(orderId);
} catch (error) {
console.log('Order fetch नहीं हुआ:', error.message);
return;
}
try {
await processPayment(order);
} catch (error) {
console.log('Payment fail हुआ:', error.message);
}
}Was this answer clear?