0
0
Javascriptprogramming~10 mins

Error handling with async and await in Javascript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to catch errors using try-catch.

Javascript
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]);
  }
}
Drag options to blanks, or click blank then click option'
Aerr
Bexception
Cerror
De
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name in catch that is not used inside the block.
Leaving the catch parentheses empty.
2fill in blank
medium

Complete the code to throw a custom error inside an async function.

Javascript
async function checkNumber(num) {
  if (num < 0) {
    [1] new Error('Negative number not allowed');
  }
  return 'Number is valid';
}
Drag options to blanks, or click blank then click option'
Athrow
Breturn
Cconsole.log
Dawait
Attempts:
3 left
💡 Hint
Common Mistakes
Using return instead of throw to signal errors.
Trying to await the error.
3fill in blank
hard

Fix the error in the async function to properly handle errors with try-catch.

Javascript
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);
  }
}
Drag options to blanks, or click blank then click option'
Aawait
Breturn
Cconsole.error
Dthrow
Attempts:
3 left
💡 Hint
Common Mistakes
Using return instead of throw inside the if statement.
Logging the error instead of throwing it.
4fill in blank
hard

Fill both blanks to create an async function that returns data or throws an error if fetch fails.

Javascript
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();
}
Drag options to blanks, or click blank then click option'
Aok
Bstatus
Cthrow
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Checking response.status instead of response.ok.
Using return instead of throw to signal error.
5fill in blank
hard

Fill all three blanks to handle errors when calling an async function with try-catch.

Javascript
async function main() {
  try {
    const data = await [1]();
    console.log('Data:', [2]);
  } catch ([3]) {
    console.error('Error caught:', [3]);
  }
}
Drag options to blanks, or click blank then click option'
AloadData
Bdata
Cerror
DfetchData
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong function name in the await call.
Not matching the catch variable name with the one used inside the block.