Complete the code to catch errors in an async function using try/catch.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch ([1]) {
console.error('Error:', error);
}
}The catch block receives the error object. Naming it error is common and matches the usage inside the block.
Complete the code to rethrow an error after logging it in an async function.
async function getUser() {
try {
const user = await fetchUserFromDB();
return user;
} catch ([1]) {
console.error('Failed to get user:', err);
throw err;
}
}The catch block uses err to log and rethrow the error, so the variable name must be err.
Fix the error in the async function to properly handle errors with try/catch.
async function loadData() {
try {
const result = await fetchData();
return result;
} catch ([1]) {
console.error('Error loading data');
}
}The catch block must include a variable to receive the error object for proper error handling and logging.
Fill both blanks to create an async function that handles errors and returns a default value.
async function fetchWithDefault() {
try {
const data = await fetchData();
return data;
} catch ([1]) {
console.error('Fetch failed:', [2]);
return null;
}
}Using the same variable name error in both blanks matches the catch parameter and the logged error.
Fill all three blanks to create an async function that tries to fetch data, logs errors, and throws a new error.
async function getData() {
try {
const response = await fetch('https://api.example.com');
const data = await response.json();
return data;
} catch ([1]) {
console.error('Fetch error:', [2]);
throw new [3]('Failed to get data');
}
}The catch parameter is err (B), the logged error is err (B), and the thrown error is a new Error object (C).