Lesson 26 - Error Handling in Async/Await
When using async/await
, handling errors properly is crucial. JavaScript provides try...catch
to manage errors in asynchronous functions.
Explanation
- Errors in an
async
function can be caught usingtry...catch
. - The
catch
block handles any rejected Promises or unexpected errors. - It prevents the program from crashing when an error occurs.
Example 1: Handling Errors with try...catch
async function fetchData() {
try {
let response = await fetch("https://invalid.url/api/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error.message);
}
}
fetchData();
- The
catch
block captures the error and logs a meaningful message instead of crashing the program.
Example 2: Rejecting a Promise and Catching the Error
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Failed to fetch data")), 1500);
});
}
async function getData() {
try {
let data = await fetchData();
console.log(data);
} catch (error) {
console.error("Error:", error.message);
}
}
getData();
- If
fetchData()
fails, thecatch
block prevents an uncaught error.
Try Your Hand
Steps:
-
Create a File:
- Name it
day27-error-handling.html
.
- Name it
-
Write the Code:
-
Copy the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Day 27 - Error Handling</title> </head> <body> <script> async function fetchData() { try { let response = await fetch("https://invalid.url/api/data"); let data = await response.json(); console.log(data); } catch (error) { console.error("Error fetching data:", error.message); } } fetchData(); </script> </body> </html>
-
-
Save the File.
-
Open Developer Console (
F12
) to See the Error Message.
Experiment
- Modify
fetchData()
to use a valid URL and see if it works. - Simulate an error inside
try
and observe howcatch
handles it.
Key Takeaways
try...catch
prevents crashes inasync
functions.- Errors should be handled gracefully with user-friendly messages.
- Always use
catch
when working with asynchronous code.