Complete the code to catch errors using try-catch.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch ([1]) {
console.error('Error:', [1]);
}
}The catch block receives the error object, commonly named error. This name is used inside the block to access the error details.
Complete the code to throw a custom error inside an async function.
async function checkNumber(num) {
if (num < 0) {
[1] new Error('Negative number not allowed');
}
return 'Number is valid';
}return instead of throw to signal errors.await the error.To signal an error, use throw followed by an Error object. This stops the function and passes the error to the caller.
Fix the error in the async function to properly handle errors with try-catch.
async function getUser() {
try {
const response = await fetch('https://api.example.com/user');
if (!response.ok) {
[1] new Error('Failed to fetch user');
}
const user = await response.json();
return user;
} catch (error) {
console.error(error);
}
}return instead of throw inside the if statement.When the response is not OK, you must throw an error to jump to the catch block. Using return or other statements won't trigger error handling.
Fill both blanks to create an async function that returns data or throws an error if fetch fails.
async function loadData() {
const response = await fetch('https://api.example.com/data');
if (!response.[1]) {
[2] new Error('Network response was not ok');
}
return response.json();
}response.status instead of response.ok.return instead of throw to signal error.The response.ok property tells if the fetch was successful. If not, you throw an error to stop execution and handle it later.
Fill all three blanks to handle errors when calling an async function with try-catch.
async function main() {
try {
const data = await [1]();
console.log('Data:', [2]);
} catch ([3]) {
console.error('Error caught:', [3]);
}
}You call the async function fetchData, store the result in data, and catch errors with the variable error.