0
0
Node.jsframework~10 mins

Why robust error handling matters in Node.js - Test Your Understanding

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.

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 fetching data:', error);
  }
}
Drag options to blanks, or click blank then click option'
Aerr
Bexception
Ce
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name in catch than inside the block.
2fill in blank
medium

Complete the code to throw a custom error when a condition fails.

Node.js
function checkAge(age) {
  if (age < 18) {
    throw new [1]('Age must be at least 18');
  }
  return true;
}
Drag options to blanks, or click blank then click option'
AException
BError
CTypeError
DRangeError
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent error classes like Exception.
3fill in blank
hard

Fix the error in the code to properly handle errors in a promise chain.

Node.js
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch([1] => console.error('Fetch error:', err));
Drag options to blanks, or click blank then click option'
Aerr
Be
Cerror
Dexception
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than inside the catch function.
4fill in blank
hard

Fill both blanks to create a try-catch block that logs the error message and rethrows the error.

Node.js
try {
  JSON.parse('[1]');
} catch ([2]) {
  console.error([2].message);
  throw [2];
}
Drag options to blanks, or click blank then click option'
A"{ invalid json }"
Berror
Cerr
D"{ key: 'value' }"
Attempts:
3 left
💡 Hint
Common Mistakes
Using valid JSON string so no error occurs.
Mismatch between catch parameter and usage.
5fill in blank
hard

Fill all three blanks to create a function that handles errors and returns a default value.

Node.js
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];
  }
}
Drag options to blanks, or click blank then click option'
Aid
Berror
C{}
DuserId
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names in URL or catch.
Returning undefined instead of a default value.