0
0
Node.jsframework~10 mins

Error handling in async/await in Node.js - 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 in an async function using try/catch.

Node.js
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);
  }
}
Drag options to blanks, or click blank then click option'
Aerror
Berr
Cexception
De
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name in catch that doesn't match the one used inside the block.
2fill in blank
medium

Complete the code to rethrow an error after logging it in an async function.

Node.js
async function getUser() {
  try {
    const user = await fetchUserFromDB();
    return user;
  } catch ([1]) {
    console.error('Failed to get user:', err);
    throw err;
  }
}
Drag options to blanks, or click blank then click option'
Aerr
Berror
Ce
Dexception
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name in catch than inside the block.
3fill in blank
hard

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

Node.js
async function loadData() {
  try {
    const result = await fetchData();
    return result;
  } catch ([1]) {
    console.error('Error loading data');
  }
}
Drag options to blanks, or click blank then click option'
Aexception
Berr
Ce
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Leaving catch parentheses empty, which prevents access to the error object.
4fill in blank
hard

Fill both blanks to create an async function that handles errors and returns a default value.

Node.js
async function fetchWithDefault() {
  try {
    const data = await fetchData();
    return data;
  } catch ([1]) {
    console.error('Fetch failed:', [2]);
    return null;
  }
}
Drag options to blanks, or click blank then click option'
Aerror
Berr
Ce
Dexception
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in catch and console.error.
5fill in blank
hard

Fill all three blanks to create an async function that tries to fetch data, logs errors, and throws a new error.

Node.js
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');
  }
}
Drag options to blanks, or click blank then click option'
Aerror
Berr
CError
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching variable names between catch and console.error.
Throwing a non-existent error class.