Node.js
try/catch
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)); // recovered
Here the catch block returns "recovered", so run() fulfils and then runs. This is the basic pattern for writing resilient code.
Exercise 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().
Show example solution
async function run() {
try {
const v = await Promise.reject(new Error("error"));
} catch (err) {
console.log(err.message);
}
}
run();
Test yourself
-
try/catch parts
- try
- risky await
- catch
- catches error
- err
- error object
-
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
- The program crashes immediately
Show answer
The async function returns a rejected Promise — An uncaught error leaves the function as a rejected Promise.
-
Fill in the blank: catch block
async function run() {
try {
await Promise.reject(new Error("hata"));
} ____ (err) {
console.log(err.message);
}
}
Show answer
async function run() {
try {
await Promise.reject(new Error("hata"));
} catch (err) {
console.log(err.message);
}
}
Next lesson: await with Promise.all