Catching what you do not await: .catch and unknown
Catch the error of a call you do not await with the promise's own .catch. See that .catch runs when the promise is rejected, after the lines below it, give its error the type unknown instead of the any it gets, check that error before you read its message, and keep a failing TaskKit reminder from stopping TaskKit.
Fundamentals
TypeScript
Catching what you do not `await`: `.catch` and `unknown`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In the last lesson a try around await caught a rejected promise,
and a try around a call with no await caught nothing: it was over
a second before the promise was rejected. Some calls you do not want
to wait for. TaskKit's remind sets one reminder and goes straight on
to the next, with no await, so no try can hold it.
A promise's error can be caught without a try. In this lesson you give a
call you do not await a catch of its own, .catch, find that its
error box is any rather than the unknown of a try's catch, and
write unknown yourself. By the end, a reminder that fails no longer
stops TaskKit.
.catch: a catch on the promise itself
.catch(callback) is the partner of then from lesson 11.3:
then runs its callback when the promise is fulfilled, .catch runs
its own when the promise is rejected, with the reason. With its dot,
.catch is a method of the promise, like then. It is not the
catch of a try; it only shares the name. You use it on a call you
do not await: with no await, nothing throws on that line, so the
promise's own .catch is the place to catch its error.
Here is brew from the last lesson, its promise caught with .catch
and not awaited. The callback checks error with instanceof Error
before it reads message, as a try's catch does; the next
section looks at the type error has here:
ts
function brew(drink: string): Promise<string> { return new Promise((resolve, reject) => { setTimeout(() => { if (drink === "Latte") { reject(new Error("Out of milk")); } else { resolve(drink); } }, 1000); });}brew("Latte").catch((error) => { if (error instanceof Error) { console.log("Sorry:", error.message); }});console.log("Order taken");
Before you press Run, follow when each part happens. Press Next
step to walk through it, or let it play:
Callstack
Timer
Promise
Terminal
Call stack: line 12line12line12
Timer: 1 second
All 9 steps shown.Step 1 of 9: Call stack: line 12Step 2 of 9: Timer: 1 secondStep 3 of 9: Promise: pendingStep 4 of 9: Call stack: line 17Step 5 of 9: Terminal: Order takenStep 6 of 9: Call stack: emptyStep 7 of 9: Promise: rejectedStep 8 of 9: Call stack: .catch callbackStep 9 of 9: Terminal: Sorry: Out of milk
All 9 steps shown.
Press Run: Order taken at once, and a second later Sorry: Out of milk, with no stack trace. No line waited for the promise: the
error went to the callback .catch had been handed. Change
"Latte" on line 12 to "Flat white" and run it again: only Order taken prints, because a fulfilled promise never calls its .catch.
unknown in catch, any in .catch
Anything can be rejected, so a try's catch gives its error box
the type unknown (lesson 11.5). In .catch, the box is not
unknown:
In a try: unknown
Does: Makes you check what it is before error.message
Never: Never lets .message through unchecked
In .catch: any
Does: Lets error.message through, whatever was rejected
Never: Never checked, until you write (error: unknown)
The same error box: unknown in a try's catch, any in .catch
The type TypeScript comes with for .catch gives the callback's
parameter the type any, an older choice it keeps so that existing
code still passes the check. The strict setting that makes a
try's catchunknown covers only a catch written with try.
As lesson 8.5 warned, any turns the check off for that box, and the
mistake reaches the run. In the two blocks below, <string> after
new Promise says what the promise would hold, as
new Map<string, Task>() said what a Map holds in lesson 10.1:
Bad — error is any, so the check
lets .message through, and a string has none.
Good — error: unknown, so the
check allows only what works on any value, such as printing it.
Run both. The first prints Sorry: undefined, with no error from the
check: a string has no message. The second prints Sorry: Out of milk: printing works on any value, so the check lets an unknown
through to console.log, as in lesson 8.5. So in .catch, write
(error: unknown) yourself, every time.
Predict the order
brew is the one from above. This time two orders go in, a latte
caught with .catch and a flat white read with then, and neither is
awaited.
Predict
What is the second line this program prints?
The common mistake: a call, not a callback
.catch needs a function it can call later, when the promise is
rejected. It is easy to hand it the line you want to run instead.
Common mistake
Handing .catch a call instead of a callback
The order should say sorry when it fails, so the call goes straight
into .catch:
Press Run: TypeScript refuses line 12 with TS2345 (TS for TypeScript,
then the number of the error), the message above, and nothing runs.
console.log("Sorry") is a call: it runs at once, on line 12, and gives back
void, nothing. The type after parameter of type is what .catch takes: a
function that gets the reason, (reason: any) => …, or no callback at all,
null or undefined. PromiseLike<never> is what that function may give
back; you can leave it aside here. A void is neither, so the check refuses
it. node, which does not check, runs the file anyway: it prints Sorry at
once, before any milk has run out, then Order taken, and a second later
still stops on Error: Out of milk.
Argument of type 'void' is not assignable to parameter of type '((reason: any) => PromiseLike<never>) | null | undefined'.
The fix
Hand .catch a function to call later: put () => in front of the
line, inside braces.
It prints Order taken, and a second later Sorry. When the check
says Argument of type 'void' where a callback belongs, look for a
call in that place: a name followed by (…) runs now, and () => in
front of it makes a function that runs later.
TaskKit: a reminder that fails
TaskKit's remind case calls remindLater without await, so that
TaskKit does not wait. That is the gap of the last lesson's common
mistake, left open on purpose: the big try around the commands is
over long before a reminder's wait ends. Today remindLater cannot
fail: it only waits for a timer. But TaskKit's waits will not always
be timers. In Module 12 it saves its tasks to a file, and a wait on a
file can fail.
1
See what a failing reminder does
In ~/projects/taskkit/index.ts, put this line right under
await delay(2000); in remindLater:
VS Code (Visual Studio Code, your editor) greys out the console.log
line under it: it can no longer run. Run a reminder with npm (Node
package manager, which runs TaskKit's scripts):
TaskKit prints its summary as before, and two seconds later Node
stops. These are the lines up to the error; the stack trace and
Node.js v24.11.1 follow them:
2
Catch it on the call
You could put await in front of each call: at the top of
index.ts, await is allowed too, and pauses the rest of the file
(lesson 11.4). The big try would then catch the error, but the loop
would wait for each reminder before setting the next, as main did
in the exercise One reminder after the other of lesson 11.4. So
catch it on the call instead. In the remind case, replace
remindLater(reminder); with these three lines:
messageOf takes an unknown (lesson 8.5), so it accepts whatever
was rejected and turns it into one sentence.
3
Check, run TaskKit, delete the test line
The check prints only its two > lines. TaskKit prints its summary,
and two seconds later one line per reminder, with no stack trace:
Now delete the throw new Error("Test: this reminder fails"); line,
and run TaskKit and its tests again:
TaskKit prints Reminder: Call Mom again after two seconds, and
npm test ends with ℹ pass 10 and ℹ fail 0, as before.
Pass all three tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one is checked in your browser. Try it before you open the hints;
they come one at a time.
Recap
Recap · 3 questions
Check yourself
When does the callback of brew("Latte").catch(…) run?
Check yourself
In order.catch((error) => …), what type is error?
Check yourself
Why does TaskKit's remind case use .catch, not its big try?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Catching what you do not await: .catch and unknown
What things are
Word
What it means
.catch(callback)
Runs the callback if the promise is rejected
Reason
What the callback gets: whatever was rejected
any in .catch
The type TypeScript gives that callback's error
Code
Write
To
(error: unknown) => …
In .catch: catch a call you do not await
error instanceof Error
Check before reading error.message
.catch(() => …)
Hand .catch a function, not a call
remindLater(…).catch(…)
Catch each reminder on its own
Rules
Rule
What it means
.catch runs later
When the promise is rejected, after the lines below
.catch gives any
Write (error: unknown) yourself
An unknown can be printed
Reading .message needs a check first
A caught rejection
The program goes on
Module 11 on one page
Each lesson's rows below are copied from its own cheat sheet. TS1308
is the error code of lesson 11.4's await mistake (TS for TypeScript,
then the number of the error).
Cheat sheet
Module 11: Asynchronous Code
11.1 What asynchronous code is and why it exists
Word or code
What it means
Asynchronous
Starts now, finishes later; the next lines go on
setTimeout(callback, 2000)
Run callback once, 2 seconds from now
The next lines go first
Lines after setTimeout run before its callback
Node waits for timers
The program ends when no timer is left
11.2 The event loop, in pictures
Word or rule
What it means
Call stack
The pile of calls under way; only the top one runs
Task queue
Callbacks whose time is up, waiting their turn
Event loop
Moves the first callback in the queue to the empty stack
One thing at a time
A timer's callback waits for the running code
11.3 Promise<T>
Word or code
What it means
Promise
An object that stands for a result still to come
Promise<string>
The type of a promise that will hold a string
resolve("Flat white")
Fulfil the promise with that value
order.then((drink) => …)
Run the callback with the value, once ready
11.4 async / await
Word or code
What it means
await
Waits for a promise, then gives you what it holds
Where to go next
You can now catch the error of a call you do not await with .catch,
give that error the type unknown yourself, and check it before you
read it. That closes Module 11: TaskKit waits, and a failed wait no
longer stops it.
Next is Module 12, Talking to the Outside World. Its first lesson
is about JSON (JavaScript Object Notation, data written as text):
JSON: parse and stringify, and why JSON.parse returns
any. That data comes from outside your code, and TypeScript
hands it to you as any, the same hole you closed in .catch
today.
Before you move on, run npm start remind "call Mom" "buy milk" once
more and watch both reminders arrive. Then say, before you look at
index.ts, what would print if remindLater failed for one of them
and not the other.
Terminal: Sorry: Out of milkSorry:OutofmilkSorry:Outofmilk
Time
Line 12 calls brew and hands .catch a callback. Nothing waits.
Node counts the second outside your code.
brew's promise: the drink is not made yet.
Line 17 prints. The file is done.
Line 17's text is out while the promise is pending.
The stack is empty while the timer counts. No try is open.
The timer's callback, which calls reject, runs too briefly to
draw.
The timer's callback calls reject with an Error: out of milk.
The promise is rejected, so its .catch callback runs with the
reason, and line 14 prints the message.
Line 14 prints. Nothing is left to wait for, so Node ends.
The file is done first; .catch runs when the promise is rejected
async function
A function that may wait; it gives back a promise
await needs async
In any other function the check stops you: TS1308
In a function, it pauses that function
The caller and the file go on
11.5 Errors in async code: try around await
Code or rule
What it means
reject(new Error("…"))
Reject the promise, and say why
await throws the reason
On its own line; the next lines are skipped
The try holds the await
A try without await is over too soon
throw in an async function
Reject the function's promise
11.6 Catching what you do not await: .catch and unknown
Code or rule
What it means
(error: unknown) => …
In .catch: catch a call you do not await
.catch runs later
When the promise is rejected, after the lines below
.catch gives any
Write (error: unknown) yourself
Exercise · Read the code
Which one is caught
brew("Latte") gives back a promise that is rejected a second later,
as in this lesson. Which of these, run on its own, lets the program
end without a stack trace?
What TaskKit printstext
> start> node index.ts remind call Mom buy milk┌ TaskKit 0.1 ───────────────┐│Your tasks, in your terminal│└────────────────────────────┘Reminder set: Call MomReminder set: Buy milk0 tasks added, room for 5 moreList 0% fullYour list, A to Z:Test: this reminder failsTest: this reminder fails
} catch (error) {
error: unknown
order.catch((error) => {
error: any
ts
const order = new Promise<string>((resolve, reject) => { reject("Out of milk");});order.catch((error) => { console.log("Sorry:", error.message);});
ts
const order = new Promise<string>((resolve, reject) => { reject("Out of milk");});order.catch((error: unknown) => { console.log("Sorry:", error);});
ts
function brew(drink: string): Promise<string> { return new Promise((resolve, reject) => { setTimeout(() => { if (drink === "Latte") { reject(new Error("Out of milk")); } else { resolve(drink); } }, 1000); });}brew("Latte").catch((error: unknown) => { if (error instanceof Error) { console.log("Sorry:", error.message); }});brew("Flat white").then((drink) => { console.log("Ready:", drink);});console.log("Orders taken");
ts
function brew(drink: string): Promise<string> { return new Promise((resolve, reject) => { setTimeout(() => { if (drink === "Latte") { reject(new Error("Out of milk")); } else { resolve(drink); } }, 1000); });}brew("Latte").catch(console.log("Sorry"));console.log("Order taken");
ts
function brew(drink: string): Promise<string> { return new Promise((resolve, reject) => { setTimeout(() => { if (drink === "Latte") { reject(new Error("Out of milk")); } else { resolve(drink); } }, 1000); });}brew("Latte").catch(() => { console.log("Sorry");});console.log("Order taken");
index.tsts
throw new Error("Test: this reminder fails");
bash
npm start remind "call Mom"
index.tsts
case "remind": for (const title of command.titles) { const reminder = capitalize(title.trim()); console.log("Reminder set:", reminder); remindLater(reminder).catch((error: unknown) => { console.log(messageOf(error)); }); } break;
bash
npm run checknpm start remind "call Mom" "buy milk"
bash
npm start remind "call Mom"npm test
What TaskKit printstext
> start> node index.ts remind call Mom┌ TaskKit 0.1 ───────────────┐│Your tasks, in your terminal│└────────────────────────────┘Reminder set: Call Mom0 tasks added, room for 5 moreList 0% fullYour list, A to Z:file:///Users/ana/projects/taskkit/index.ts:17 throw new Error("Test: this reminder fails"); ^Error: Test: this reminder fails
> start> node index.ts remind call Mom┌ TaskKit 0.1 ───────────────┐│Your tasks, in your terminal│└────────────────────────────┘Reminder set: Call Mom0 tasks added, room for 5 moreList 0% fullYour list, A to Z:file:///C:/Users/ana/projects/taskkit/index.ts:17 throw new Error("Test: this reminder fails"); ^Error: Test: this reminder fails
> start> node index.ts remind call Mom┌ TaskKit 0.1 ───────────────┐│Your tasks, in your terminal│└────────────────────────────┘Reminder set: Call Mom0 tasks added, room for 5 moreList 0% fullYour list, A to Z:file:///home/ana/projects/taskkit/index.ts:17 throw new Error("Test: this reminder fails"); ^Error: Test: this reminder fails
Exercise · Fix the error
Read the reason
This program runs and prints Sorry: undefined. Make it print
Sorry: Out of tea, with error typed so that TypeScript's check
would have refused error.message.
Loading the editor…
Exercise · Write the code
Catch every order
This program prints Orders taken, then stops on Error: Out of milk.
Without await, give each call in the loop its own .catch, so that
it prints Orders taken, then Sorry: Out of milk twice.