Handling rejections with try/catch and await in JavaScript means putting the awaited work inside the try block and letting the catch block receive the failure as an ordinary error object. It reads like synchronous code, and the only real trap is knowing exactly which lines the catch block is allowed to see. The previous lesson in this module explained how await pauses a function, and the next lesson in this module puts several of these techniques together in a real fetching workflow.
The previous lesson in this module covered "async/await: Sequential vs Parallel Waiting", and the next lesson in this module is about "Fetching Data in Sequence and in Batch".
What does a try block catch when the work is asynchronous?
Everything between try and catch, including the code that runs after an await. The await suspends the function, and when the awaited promise rejects, the rejection is thrown back into that same function at the point of the await, where the catch block can pick it up.
function wait(ms, value) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(value);
}, ms);
});
}
async function getPort() {
try {
const port = await wait(50, 80);
if (port < 1024) {
throw new Error('port ' + port + ' needs elevated privileges');
}
return 'listening on port ' + port;
} catch (error) {
return 'falling back: ' + error.message;
}
}
getPort().then(function (message) {
console.log(message);
});
The output shows two different failures handled by the same block. The awaited value was fine, but the check that you did on it threw:
falling back: port 80 needs elevated privileges
Two different failures produce the same shape of response here. A rejected promise and an ordinary throw are indistinguishable once they reach the catch block, and that is exactly what you want, because one place then decides what to do about failure.
That same fact means a catch block can swallow errors that it was never meant to handle. A typo in the code between the try and the catch lands in the same place as a network failure, and the fallback message hides a real bug behind a friendly string. When you catch broadly, log the error before you fall back, so that the real cause is still recorded somewhere.
Why does a try block miss a rejection when the await is missing?
Because try only catches work that is still running while the block is on the stack. Call an async function without awaiting it and it returns a promise immediately, so the function is suspended and the try block has already moved on. The rejection then arrives with nobody listening for it.
async function saveRecord() {
throw new Error('the disk is full');
}
try {
saveRecord();
console.log('the try block finished without complaint');
} catch (error) {
console.log('the catch block ran:', error.message);
}
The output is:
the try block finished without complaint
The catch block never ran. The try block reported success because the failure had not happened yet, and the error escaped to the top level as an unhandled rejection, which your browser or your console will report separately. The fix is to await the call, or to attach a catch to the promise that it returns.
How do you catch a rejection from a promise you did not create?
Often the promise comes from somewhere else, such as a library, a request helper, or another function that returns a promise instead of throwing. Awaiting it inside your own try block catches it in exactly the same way, because awaiting a rejected promise throws.
function getUser(id) {
if (id === 7) {
return Promise.reject(new Error('user ' + id + ' was deleted'));
}
return Promise.resolve({ id: id, name: 'Grace' });
}
async function showUser(id) {
try {
const user = await getUser(id);
console.log('user:', user.name);
} catch (error) {
console.log('could not load the user:', error.message);
}
}
showUser(7);
showUser(3);
Both calls were handled independently:
could not load the user: user 7 was deleted
user: Grace
The failing lookup did not stop the second one. A catch block that swallows the error and returns a sensible default is a perfectly good design, and the important part is that the decision is written down rather than accidental.
When does finally earn its place?
Use finally for cleanup that must happen whether the work succeeded or failed, such as hiding a spinner, releasing a lock, closing a connection, or resetting a form field. It runs after the try or the catch, and it cannot replace either one of them.
function wait(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
}
async function work() {
console.log('spinner on');
try {
await wait(60);
console.log('work finished');
} catch (error) {
console.log('work failed:', error.message);
} finally {
console.log('spinner off');
}
}
work();
The output is:
spinner on
work finished
spinner off
Notice that the finally block runs last on every path, including the failing one. That is why it beats duplicating the cleanup line in both the try and the catch.
What if only some of the work fails?
Promise.all gives up on the whole batch as soon as one promise rejects, so you lose the results of the ones that succeeded. When every item matters and a partial success is acceptable, Promise.allSettled waits for all of them and then reports each outcome separately.
function settle(name, ok) {
if (ok) {
return Promise.resolve(name);
}
return Promise.reject(new Error(name + ' failed'));
}
async function main() {
const results = await Promise.allSettled([
settle('alpha', true),
settle('beta', false),
settle('gamma', true),
]);
for (const result of results) {
if (result.status === 'fulfilled') {
console.log('ok:', result.value);
} else {
console.log('failed:', result.reason.message);
}
}
}
main();
The output keeps the two good results and reports the bad one:
ok: alpha
failed: beta failed
ok: gamma
Each entry in the results array is an object with a status of fulfilled or rejected, and it holds either the value or the reason. Nothing is thrown, so you get to decide what a partial failure means for your program.
The trade-off is that you now own the checking. With Promise.all you either get a full array of values or an exception. With Promise.allSettled you get an array of mixed outcomes and you have to inspect every entry. Use the first one when a single missing record makes the whole result useless, and use the second one when each record stands on its own.
How do you add context without losing the original failure?
When a low-level function fails, the useful message is often one layer higher up, because it should say which operation failed and for which record. The Error constructor accepts a second argument with a cause property, so the new message can point at the operation while the original error stays reachable.
async function readRecord(id) {
await new Promise(function (resolve) {
setTimeout(resolve, 20);
});
throw new Error('record ' + id + ' is missing');
}
async function loadProfile(id) {
try {
const raw = await readRecord(id);
return JSON.parse(raw);
} catch (error) {
throw new Error('could not load profile ' + id, { cause: error });
}
}
loadProfile(9).catch(function (error) {
console.log('outer:', error.message);
console.log('cause:', error.cause.message);
});
The output shows both messages:
outer: could not load profile 9
cause: record 9 is missing
Re-throwing with a cause keeps the details of the original failure and adds the context of the new one. Logging both of them is usually more helpful than logging either one alone.
A retry loop is the other common reaction to a rejection, and it belongs around the awaited call rather than around the whole function.
async function withRetry(task, attempts) {
let lastError;
for (let i = 1; i <= attempts; i += 1) {
try {
return await task();
} catch (error) {
lastError = error;
console.log('attempt ' + i + ' failed:', error.message);
}
}
throw lastError;
}
let calls = 0;
async function flaky() {
calls += 1;
if (calls < 3) {
throw new Error('temporary glitch');
}
return 'saved after ' + calls + ' attempts';
}
withRetry(flaky, 3).then(function (result) {
console.log(result);
});
The output shows two failures and then a third attempt that succeeds:
attempt 1 failed: temporary glitch
attempt 2 failed: temporary glitch
saved after 3 attempts
Rejection-handling rules of thumb
- Put the awaited call inside the try block, because the catch block only sees failures that happen while the block is still running.
- If you call an async function without awaiting it, the try block cannot catch its rejection.
- Awaiting a rejected promise throws, so one catch block handles both rejected promises and thrown errors.
- Use finally for cleanup that must run on every path, and not for deciding what the failure means.
- Use
Promise.allSettledwhen partial results are still worth keeping. - Wrap an error with a cause when the low-level message does not say which operation failed.
- Never end a catch block with an empty body. Log the error, re-throw it, or return a deliberate fallback.
Try it yourself: Write an async function that waits for a promise which rejects with the message "temporary glitch" the first two times that it is called and resolves on the third. Wrap it in the retry helper from this lesson and print each attempt. Then remove the await from the call site, run the file again, and confirm that the rejection now escapes as an unhandled rejection instead of being caught. Finally, swap Promise.all for Promise.allSettled over a list where one item fails, and check that the successful items still reach your results array.