Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to catch errors from the promise.
Javascript
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .[1](error => console.error('Error:', error));
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using .then() instead of .catch() for error handling
Using .finally() to catch errors
✗ Incorrect
The .catch() method is used to handle errors in a promise chain.
2fill in blank
mediumComplete the code to handle errors using async/await with try-catch.
Javascript
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch ([1]) {
console.error('Error:', error);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than the one used in console.error
Leaving the catch parameter empty
✗ Incorrect
The catch block receives the error object, commonly named 'error' here.
3fill in blank
hardFix the error in the promise chain to properly handle errors.
Javascript
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .[1](error => console.log('Error:', error));
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like .error or .fail
Trying to handle errors inside .then() without catch
✗ Incorrect
The correct method to handle errors in promises is .catch(), not .error or others.
4fill in blank
hardFill both blanks to create a promise that rejects and handle the error.
Javascript
const promise = new Promise((resolve, [1]) => { [2]('Failed to load data'); }); promise.catch(error => console.log(error));
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using resolve instead of reject to signal failure
Not calling reject inside the promise
✗ Incorrect
The second parameter of the Promise constructor is reject, which is called to reject the promise.
5fill in blank
hardFill all three blanks to handle errors and always run cleanup code.
Javascript
fetch('https://api.example.com/data') .then(response => response.json()) .catch([1] => console.error('Error:', [2])) .[3](() => console.log('Cleanup done'));
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for catch parameter and variable
Using .catch() instead of .finally() for cleanup
✗ Incorrect
The catch block uses 'error' as parameter and variable, and finally runs cleanup code.