JavaScript Errors in async Functions
A throw inside an async function becomes a rejection. A try/catch around await catches the rejection in place.
A throw becomes a rejection
The async function throws an error. The throw rejects the returned promise, and catch logs the error name and message.
async function broken() {
throw new Error("Something broke");
}
broken().catch((err) => console.log(err.name + ": " + err.message));Catch around await
The awaited promise rejects after a short timer. The catch block logs the message, and the line after the try block never runs.
function fail() {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Timed out")), 50);
});
}
(async () => {
try {
await fail();
console.log("No error");
} catch (err) {
console.log("Caught: " + err.message);
}
})();Fall back after a catch
The awaited promise rejects, so the catch sets a fallback score. The function then logs the fallback value.
(async () => {
let score = 0;
try {
score = await Promise.reject(new Error("No score"));
} catch (err) {
console.log("Using fallback");
score = 10;
}
console.log(score);
})();Example
async function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
divide(10, 0)
.then((value) => console.log(value))
.catch((err) => console.log("Error: " + err.message));Key points
- A throw inside an async function rejects the promise it returns.
- try/catch around an await catches the rejection from that await.
- The catch block runs when the awaited promise rejects.
- A caught error can fall back to a safe value, so the function carries on.
- A caller can also catch the rejection with catch on the returned promise.
- An uncaught rejection in an async function is an error the script never handled.
In this example, the divide function is async, so its throw becomes a rejection. The then step is skipped, and the catch logs the error message.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What happens to a throw inside an async function?