Handling errors in asynchronous JavaScript code is crucial to ensure your applications run smoothly and can recover gracefully from unexpected issues. This lesson covers various methods for handling errors in asynchronous code, including try/catch with async/await, and .catch with promises.
When working with promises, errors can be handled using the .catch method.
Example: Promise Error Handling
fetchData('https://example.com/api')
.then(function(data) {
console.log('Data:', data);
})
.catch(function(error) {
console.error('Error:', error);
});
This example demonstrates how to handle errors using the .catch method when working with promises.
Using async/await provides a more readable way to work with asynchronous code. Errors can be handled using try/catch blocks.
Example: Async/Await Error Handling
async function getData() {
try {
let data = await fetchData('https://example.com/api');
console.log('Data:', data);
} catch (error) {
console.error('Error:', error);
}
}
getData();
This example demonstrates how to handle errors using try/catch blocks in an async function.
You can combine async/await with .catch for more comprehensive error handling.
Example: Combined Error Handling
// Async function with combined error handling
async function getData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
console.log(JSON.stringify(data));
} catch (error) {
console.error('Caught by try/catch:', error);
}
}
getData().catch(error => console.error('Caught by .catch:', error));
This example demonstrates how to combine try/catch with .catch for handling errors in asynchronous code.
Here are some important notes and best practices for handling errors in asynchronous JavaScript code:
Effective error handling in asynchronous JavaScript code is essential for building robust applications. By understanding and applying these techniques, you can ensure your code can gracefully handle errors and continue to function correctly.