try/catch
- Node.js course
- Beginner
- Lesson 96/116
- 5 min
Learn to catch errors in async functions with try/catch.
Catch errors with try/catch
To catch errors in an async function you use a try/catch block. You put the await call inside try; if the Promise rejects, flow jumps to the catch block and you handle the error.
async function run() {
try {
const v = await Promise.reject(new Error("err"));
} catch (err) {
console.error(err.message);
}
}This is the same shape as synchronous error handling, which makes async code easy to read. If you return a value from the catch block, the function resolves with that value as if it had recovered.
Recovering with catch
After catching an error, the catch block can return a normal value; the async function then fulfils as if it had recovered. This lets you take an alternative path after an error.
async function run() {
try {
await Promise.reject(new Error("x"));
} catch (err) {
return "recovered";
}
}
run().then(v => console.log(v)); // recoveredHere the catch block returns "recovered", so run() fulfils and then runs. This is the basic pattern for writing resilient code.
Practice Your turn: try/catch with await
Define async function run(). Inside a try block, write const v = await Promise.reject(new Error("error")). Inside catch (err), write console.log(err.message). Finally call run().
Starter code
// Define async function run
// try: await Promise.reject; catch: console.log(err.message)
// Finally call runSample solution
async function run() {
try {
const v = await Promise.reject(new Error("error"));
} catch (err) {
console.log(err.message);
}
}
run();Expected output
error
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 try/catch parts
| Term | Meaning |
|---|---|
try |
risky await |
catch |
catches error |
err |
error object |
2 If the Promise awaited rejects and there is NO try/catch, what happens?
- await's value becomes undefined
- The Promise is automatically fulfilled
- The async function returns a rejected Promise Correct answer
- The program crashes immediately
Explanation: An uncaught error leaves the function as a rejected Promise.
3 Fill in the blank: catch block
async function run() {
try {
await Promise.reject(new Error("hata"));
} ____ (err) {
console.log(err.message);
}
}
async function run() {
try {
await Promise.reject(new Error("hata"));
} catch (err) {
console.log(err.message);
}
}
Explanation: catch takes the error as a parameter.