Complete the code to catch errors in an async function.
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 fetching data:', error);
}
}The catch block uses the variable error to hold the caught error. This variable is then used inside the block.
Complete the code to throw a custom error when a condition fails.
function checkAge(age) {
if (age < 18) {
throw new [1]('Age must be at least 18');
}
return true;
}Throwing a new Error object is the standard way to create custom errors in JavaScript.
Fix the error in the code to properly handle errors in a promise chain.
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch([1] => console.error('Fetch error:', err));
The catch block uses err as the parameter, which matches the variable used inside the arrow function.
Fill both blanks to create a try-catch block that logs the error message and rethrows the error.
try { JSON.parse('[1]'); } catch ([2]) { console.error([2].message); throw [2]; }
The string "{ invalid json }" is invalid JSON and will cause an error. The catch block uses error to log and rethrow the error.
Fill all three blanks to create a function that handles errors and returns a default value.
async function getUser(id) {
try {
const response = await fetch(`/users/$[1]`);
if (!response.ok) throw new Error('User not found');
return await response.json();
} catch ([2]) {
console.error([2].message);
return [3];
}
}The function uses id in the URL, catches errors with error, logs the message, and returns an empty object {} as a default value.