Complete the code to catch errors using try/catch with async/await.
async function fetchData() {
try {
const data = await fetch('[1]');
return data.json();
} catch (error) {
console.error('Error:', error);
}
}The fetch function needs a URL string as argument. Here, the URL is passed as a string inside quotes.
Complete the code to rethrow an error after logging it inside a catch block.
async function getUser() {
try {
const response = await fetch('/user');
return await response.json();
} catch (error) {
console.error('Fetch failed:', error);
[1];
}
}To pass the error up the call stack after logging, use throw error.
Fix the error in this async function by adding proper error handling.
async function loadData() {
const response = await fetch('/data');
const json = await response.json();
return json;
[1]
}To handle errors in async/await, wrap the await calls inside a try/catch block.
Fill both blanks to create an async function that returns null on error instead of throwing.
async function safeFetch() {
try {
const response = await fetch('[1]');
return await response.json();
} catch ([2]) {
return null;
}
}The function fetches from '/safe-data' and catches errors using the variable named error.
Fill all three blanks to create an async function that logs error message and returns fallback data.
async function fetchWithFallback() {
try {
const res = await fetch('[1]');
if (!res.ok) throw new Error(res.statusText);
return await res.json();
} catch ([2]) {
console.error('Fetch error:', [3].message);
return { data: [] };
}
}The function fetches from '/api/items', catches errors as err, logs err.message, and returns fallback data.