Where to throw and where to catch: friendly errors for bad commands
Refuse a bad command where it is read, catch the refusal once where the program talks to the person, and write error messages that say what to type instead. Give TaskKit one friendly line for every command it does not know, and see why a catch that has to make up an answer is in the wrong place.
Fundamentals
TypeScript
Where to throw and where to catch: friendly errors for bad commands. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Ask TaskKit for a command it does not have, and it tells you so, then
carries on as if you had asked for something. Run
node index.ts remove in ~/projects/taskkit and look under the
banner:
Outputtext
Unknown command: removeRun node index.ts help to see the commandsTasks added: 0 of 5, room for 5 moreList 0% fullYour list, A to Z:
Two lines for you, then a summary of a list nobody asked for. In the
last lesson the cook who found no eggs did not send out an empty
plate: the order went back to the waiter, who talks to the guest.
TaskKit has a cook and a waiter too. In this lesson each of them gets
its job, and a bad command gets one line that says what to type
instead.
Refuse where you check
TaskKit reads what you typed in one place: readCommand. It looks at the word
after node index.ts, and it is the only part of the program that knows which
words are commands. That makes it the edge of TaskKit, the line between
what you typed and what the program works with. A word that is not a command
is found there, so it is refused there, with throw, as bar refused a count
it could not draw.
Today readCommand does not refuse. It hands back a command of the
kind "unknown", and the switch at the bottom of index.ts prints
the two lines about it. Then the program goes on to the summary and
the list, because as far as it knows, a command came back. A bad
command is not a command, so readCommand should not hand one back.
Catch where you talk
If nothing catches the refusal, Node stops TaskKit and prints a stack
trace, as it stopped bar.ts in the last lesson. So it has to be
caught, and the place is where TaskKit talks to you: the bottom of
index.ts, where it prints. One try there holds everything from
readCommand() to the list, and its catch prints the error's
message.
Here is where a good command and a bad one go once TaskKit works
that way, as this lesson's step will make it. Choose one at the top
of the figure, press Next step to walk through it, or let it
play:
command
switch
summary
catch
command: returnsreturnsreturns
switch: addsaddsadds
summary: printsprintsprints
catch: skippedskippedskipped
Time
readCommand knows add: it gives back
{ kind: "add", titles: ["pay rent"] }.
The add case adds the task and prints Added: Pay rent.
printSummary and printList print the count and the list.
Nothing was thrown, so the catch never runs.
A refused command skips the switch, the summary and the
list, up to the catch
All 4 steps shown.Step 1 of 4: command: returnsStep 2 of 4: switch: addsStep 3 of 4: summary: printsStep 4 of 4: catch: skipped
All 4 steps shown.
command
switch
summary
catch
command: throwsthrowsthrows
switch: skippedskippedskipped
summary: skippedskippedskipped
catch: printsprintsprints
Time
readCommand knows no remove, so it throws.
No command came back, so the switch never runs.
Skipped with the rest of the try: no summary is printed.
Unknown command: remove. Try: node index.ts help, and nothing
else.
A refused command skips the switch, the summary and the
list, up to the catch
All 4 steps shown.Step 1 of 4: command: throwsStep 2 of 4: switch: skippedStep 3 of 4: summary: skippedStep 4 of 4: catch: prints
All 4 steps shown.
That is the cook and the waiter. readCommand is the cook: it finds
the problem, and refuses. The catch is the waiter: the one place
that decides what to tell you. Neither does the other's job.
A message that says what to do
Whatever the catch prints is all the person learns about the
problem, so the message has to be enough on its own.
Bad — the message says that
something is wrong, and nothing else.
hint.tsts
function checkWord(word: string): string { if (word !== "add" && word !== "help") { throw new Error("Bad command"); } return word;}try { console.log(checkWord("remove"));} catch (error) { if (error instanceof Error) { console.log(error.message); }}
Good — the message names what was
typed, and what to type instead.
hint.tsts
function checkWord(word: string): string { if (word !== "add" && word !== "help") { throw new Error(`Unknown command: ${word}. Try: help`); } return word;}try { console.log(checkWord("remove"));} catch (error) { if (error instanceof Error) { console.log(error.message); }}
Run both. The first prints Bad command, and the person has to
guess which word was bad and what would have worked. The second
prints Unknown command: remove. Try: help: what went wrong, and
the next thing to type. The message is written where the problem is
found, because only that line knows what was wrong.
TaskKit: one line for every bad command
Now TaskKit's step for this module.
1
Make readCommand refuse
In index.ts in ~/projects/taskkit, Command loses its two
shapes for bad commands. Replace it with these four lines:
In readCommand, replace the four lines from case undefined: to
return { kind: "unknown", word: word }; with these:
index.tsts
case undefined: throw new Error("Which command? Try: node index.ts help"); default: const lower = word.toLowerCase(); if (lower === "add" || lower === "help" || lower === "version") { throw new Error(`Commands are in lower case. Try: ${lower}`); } throw new Error(`Unknown command: ${word}. Try: node index.ts help`);
The lower-case hint goes only to a real command typed with capitals, such as
Add: for any other word, a hint to type it in lower case would send the
person to a command that does not exist either. readCommand still promises a
Command, and keeps the promise every time it returns. A throw never
returns at all, so TypeScript accepts a case that throws instead of returning.
2
Catch the refusal
At the bottom of the file, the switch still has its case "missing": and case "unknown":, and VS Code (Visual Studio Code,
your editor) now underlines five new errors, all in those two cases:
no command has those kinds any more. The first reads Type '"missing"' is not comparable to type '"add" | "help" | "version"'. Delete both
cases, with every line under them, and keep the } that closes the
switch.
Then put try { on a line of its own above
const command = readCommand();, and add these lines under the
last line of the file, printList(tasks);:
Drag over the lines between try { and } catch with the mouse to
select them, and press Tab: VS Code moves them one step in,
so the code shows what is inside the try. The banner stays above the
try, so it prints first, whatever command was typed.
3
Check, run TaskKit, run the tests
Check the file with tsc (short for TypeScript compiler), which
npx starts, then run TaskKit and the tests:
============================TaskKit 0.1Your tasks, in your terminal============================Unknown command: remove. Try: node index.ts help
node --test still counts pass 7, and add, help and
version print what they printed before.
readCommand makes three checks before it hands a command back, and
each bad command stops at the first one it fails. Pick a command at
the top of the figure, press Next step to walk it through the
checks, or let it play:
% node index.ts add"pay rent"
Typed
✓passes: Acommandatall?
✓passes: Notacommandincapitals?
✓passes: Acommanditknows?
Runthecommand
add
TaskKit printsAdded: Pay rent
Each bad command is refused at the edge, with its own line
All 5 steps shown.Step 1 of 5: Typed: add pay rentStep 2 of 5: A command at all?: yesStep 3 of 5: Not a command in capitals?: yesStep 4 of 5: A command it knows?: yesStep 5 of 5: Inside: Added: Pay rent
All 5 steps shown.
% node index.ts
Typed
✕fails: Acommandatall?
not checked yet: Notacommandincapitals?
not checked yet: Acommanditknows?
Runthecommand
TaskKit answersWhich command? Try: node index.ts help
Each bad command is refused at the edge, with its own line
All 3 steps shown.Step 1 of 3: Typed: Step 2 of 3: A command at all?: noStep 3 of 3: Stopped: Which command? Try: node index.ts help
All 3 steps shown.
% node index.ts Add
Typed
✓passes: Acommandatall?
✕fails: Notacommandincapitals?
not checked yet: Acommanditknows?
Runthecommand
Add
TaskKit answersCommands are in lower case. Try: add
Each bad command is refused at the edge, with its own line
All 4 steps shown.Step 1 of 4: Typed: AddStep 2 of 4: A command at all?: yesStep 3 of 4: Not a command in capitals?: noStep 4 of 4: Stopped: Commands are in lower case. Try: add
All 4 steps shown.
% node index.ts remove
Typed
✓passes: Acommandatall?
✓passes: Notacommandincapitals?
✕fails: Acommanditknows?
Runthecommand
remove
TaskKit answersUnknown command: remove. Try: node index.ts help
Each bad command is refused at the edge, with its own line
All 5 steps shown.Step 1 of 5: Typed: removeStep 2 of 5: A command at all?: yesStep 3 of 5: Not a command in capitals?: yesStep 4 of 5: A command it knows?: noStep 5 of 5: Stopped: Unknown command: remove. Try: node index.ts help
All 5 steps shown.
A new check later is one more throw in readCommand, with its
message beside it, and the catch at the bottom already prints it.
Predict what it prints
With TaskKit as it is after the step, you type a real command in
capitals, with a task after it: node index.ts ADD "pay rent".
Predict
What does it print after the banner?
index.tsts
default: const lower = word.toLowerCase(); if (lower === "add" || lower === "help" || lower === "version") { throw new Error(`Commands are in lower case. Try: ${lower}`); } throw new Error(`Unknown command: ${word}. Try: node index.ts help`);
The common mistake: catching too early
The catch belongs where the program talks to the person. It is
tempting to put it right next to the throw instead, so that
readCommand deals with its own problem.
Common mistake
A catch inside readCommand
You wrap the switch inside readCommand in a try, print the
message in its catch, and give back the help command, because a
function that promises a Command has to give back one:
index.tsts
try { switch (word) { // the cases as before, the throws included } } catch (error) { if (error instanceof Error) { console.log(error.message); } return { kind: "help" }; }
TypeScript finds nothing wrong. Run node index.ts remove, and under
the banner TaskKit prints:
Outputtext
Unknown command: remove. Try: node index.ts helpCommands: add "task", help, versionTasks added: 0 of 5, room for 5 moreList 0% fullYour list, A to Z:
The catch printed the message, then readCommand gave back a
command nobody typed. The program ran it, then the summary and the
list, the very lines this step was meant to stop.
Tasks added: 0 of 5, room for 5 more
The fix
Take the try and the catch out of readCommand, so it only
refuses, and leave the one catch at the bottom of index.ts, as
the step wrote it. node index.ts remove prints one line again.
A function that cannot do its job has nothing honest to give back. If
a catch inside it has to make up an answer, it is in the wrong
place: let the refusal go on to the part of the program that can
answer the person.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each exercise is checked in your browser. Press Check when you
think you have it; if you are stuck, the hints come one at a time.
Exercise · Predict the result
A capital letter in TaskKit
You run node index.ts Remove with TaskKit as it is after this
lesson's step. What is the first word it prints after the banner?
Exercise · Fix the error
Refuse, and let the caller answer
readMinutes catches its own refusal, prints a vague line and gives
back a fake 0, so the program prints Planned: 0 minutes. Take the
try and catch out of readMinutes, so it only refuses. Then let
the bottom of the file answer the person: wrap the two console.log
lines so that a refusal prints its message. It should print
Planned: 25 minutes, then Not a number: soon. Try: 25.
Number.isNaN asks whether minutes is NaN (not a number), the
value Number gives back for text like "soon" (lesson 2.5).
Loading the editor…
Exercise · Read the code
Which line prints it
The program prints Not a number: soon. Try: 25. Which line prints
it?
ts
function readMinutes(typed: string): number { const minutes = Number(typed); if (Number.isNaN(minutes)) { throw new Error(`Not a number: ${typed}. Try: 25`); } return minutes;}function plan(typed: string): string { const minutes = readMinutes(typed); return `Planned: ${minutes} minutes`;}try { console.log(plan("soon"));} catch (error) { if (error instanceof Error) { console.log(error.message); }}
Exercise · Write the code
A title rule with a helpful message
Write readTitle. It takes what was typed, trims the spaces around
it, and gives back the trimmed title. A title that is empty after
trimming throws an Error with the message
A task needs a title. Try: add "pay rent". A title longer than 40
characters throws one with the message
A title is at most 40 characters, not 42, with the real length in
place of 42. The two lines at the bottom should print pay rent,
then the message for the long title.
Loading the editor…
Recap
Recap · 3 questions
Check yourself
Where should a bad command be refused?
Check yourself
Why is TaskKit's catch at the bottom of index.ts?
Check yourself
What makes an error message helpful?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Where to throw and where to catch
What things are
Word
What it means
Edge
Where typed words come into the program
Refusal
A throw at the check that found the problem
One catch
Where the program talks to the person
Helpful message
What went wrong, and what to type instead
Code
Write
To
throw new Error("… Try: …")
Refuse, and say what to type
try { … } around the program
Hold every line a refusal may skip
catch (error) { … } at the bottom
Print the one line
throw in a case
End a case without a return
Rules
Rule
What it means
Refuse where you check
The line that finds it throws
Catch where you talk
Where the program prints to the person
No made-up answer
A catch that must invent one is too early
A wide catch
Also catches bugs, and hides their line
Where to go next
You can now refuse a bad command where it is read, catch the refusal
once where TaskKit talks to the person, and write a message that says
what to type instead. TaskKit answers a command it does not know with
one line.
Next is any vs unknown: the escape hatch and the safe box. You met
unknown as the type of a caught error in the last lesson, and checked it
with instanceof before reading its message. That lesson shows where else
it comes from, and why any, which looks as if it does the same, lets
mistakes through.
Before you move on, give TaskKit's add a rule of its own. If you
gave TaskKit lesson 3.2's 40-character rule, take it out and use a
throw in its place; if not, add it now. In the add case, right under
const tidyTask = typed.trim();, throw new Error(`A title is at most 40 characters, not ${tidyTask.length}`) when tidyTask.length
is more than 40. Run add with three titles, the second one too long,
and predict first: which tasks are added, and is the summary printed?
Then decide whether a long title should stop the whole command, or be
skipped the way an empty one is.