JavaScript Fundamentals · Error Handling · Lesson 32 of 48
Handling Errors in Async Code
Concept
Handling Errors in Async Code
try/catch also works with await, and Promises have their own .catch() method — both let you handle failures from asynchronous operations cleanly.
An unhandled rejected Promise doesn't crash Node.js or the browser immediately the way a thrown synchronous error does, but it will log a warning and is worth catching explicitly.
- Explain the core idea behind Handling Errors in Async Code.
- Predict output before running a change.
- Test one realistic and one unusual input.
- Use the result to make the next decision.
- 1. Read one concept.
- 2. Change the example.
- 3. Run, compare, and explain.
- 4. Complete the challenge below.
async function name() {
try {
await somePromise;
} catch (error) {}
}async function loadUser() {
try {
const response = await fetch("/api/user");
const user = await response.json();
console.log(user);
} catch (error) {
console.log("Failed to load user:", error.message);
}
}Try it Yourself »fetch("/api/user")
.then((res) => res.json())
.catch((error) => console.log("Failed:", error.message));Self-check before continuing
Without looking at the example, describe what changes when you modify one input in Handling Errors in Async Code. Then reopen the editor and prove your explanation with a small test.
You are ready to continue when you can predict, test, and explain the result.
Your turn
Write an async function that awaits a rejected Promise inside a try/catch and logs a fallback message.
Console