Sub topic 9
Handling errors and setting exit codes
This chapter covers how the wcl tool reports failure. It explains what a failure looks like to the shell, how to catch errors in Node.js without hiding them, and how to set the process exit code safely. It assumes you have the project from the earlier chapters: parseArgs for arguments, countText as a pure function, and readFile from node:fs/promises. You should be comfortable with try/catch and async/await.
Why exit codes matter
A command-line program talks to two audiences. A person reads the text it prints. Other programs, such as shell scripts, CI jobs, and make, read only its exit code. The exit code is a small integer the process hands back to its parent when it ends.
By convention, 0 means success and any other value means failure. A script like this depends on that convention:
wcl report.txt && echo "counted" || echo "failed"If wcl printed an error but still exited with 0, the script would report "counted". The message would be correct and the program would still be wrong. Exit codes are part of your tool's interface, just like its flags.
Choosing a small set of codes
Keep the set small and document it. This tutorial uses three values:
| Code | Meaning | Example |
|---|---|---|
| 0 | Success | The file was read and counted |
| 1 | Runtime failure | The file is missing, unreadable, or a directory |
| 2 | Usage error | No file argument, or an unknown flag |
Separating 1 from 2 lets a caller tell "you invoked me wrongly" from "the world did not cooperate". Many Unix tools follow this split, though no rule forces it. Avoid codes above 125. Shells reserve many of them for their own meanings, such as 126 for "found but not executable", 127 for "command not found", and 128 plus N for death by signal N.
Where errors come from
The tool has two failure sources, and they behave differently.
- Argument errors happen before any I/O.
parseArgsthrows aTypeErrorwith acodesuch asERR_PARSE_ARGS_UNKNOWN_OPTIONwhen it sees a flag you did not declare. A missing file argument is a case your own code detects. - I/O errors happen while reading. Node rejects the promise from
readFilewith anErrorthat carries a stringcodesuch asENOENT(no such file),EISDIR(path is a directory), orEACCES(permission denied).
Both should end in a message on stderr and a non-zero exit code. The difference is which code you choose.
What you can safely assume about a caught value
In TypeScript with strict enabled, the variable in catch (err) has type unknown. That is the correct type, because JavaScript lets code throw anything, including strings and undefined. You must narrow it before reading properties.
function describeError(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}Node's system errors are ordinary Error objects with extra properties. The check "code" in err narrows the type so that err.code is readable, but its type is still unknown. Compare it to string literals instead of casting it.
function describeFsError(err: unknown, file: string): string {
if (err instanceof Error && "code" in err) {
switch (err.code) {
case "ENOENT":
return `${file}: no such file`;
case "EISDIR":
return `${file}: is a directory`;
case "EACCES":
return `${file}: permission denied`;
}
}
return describeError(err);
}The function maps known codes to short messages and falls back to Node's own message for anything else. The fallback matters: an unexpected failure should still be reported, not swallowed.
A typed error for usage problems
You could return a number from every helper, but that clutters the code. A small error class lets any layer signal "this is a usage error" and lets one place decide what to do with it.
export class UsageError extends Error {
constructor(message: string) {
super(message);
this.name = "UsageError";
}
}Now validation code can throw new UsageError("missing file argument"). The top-level handler checks err instanceof UsageError and picks exit code 2. Every other error gets exit code 1.
This keeps policy in one function. The helpers describe what went wrong, and main decides how that maps to the outside world.
How control flows
The diagram shows the path through main. Every route ends at a return value, and only the entry point turns that value into an exit code.
The complete entry point
Here is the earlier main rewritten with the pieces above. It is one file, src/cli.ts, and it still depends on countText from src/count.ts.
#!/usr/bin/env node
import { readFile } from "node:fs/promises";
import { countText } from "./count.js";
class UsageError extends Error {
constructor(message: string) {
super(message);
this.name = "UsageError";
}
}
function describeError(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
function describeFsError(err: unknown, file: string): string {
if (err instanceof Error && "code" in err) {
switch (err.code) {
case "ENOENT":
return `${file}: no such file`;
case "EISDIR":
return `${file}: is a directory`;
case "EACCES":
return `${file}: permission denied`;
}
}
return describeError(err);
}
async function run(argv: string[]): Promise<void> {
const file = argv[0];
if (!file) {
throw new UsageError("usage: wcl <file>");
}
let text: string;
try {
text = await readFile(file, "utf8");
} catch (err) {
throw new Error(describeFsError(err, file));
}
const { lines, words } = countText(text);
console.log(`${lines} ${words} ${file}`);
}
async function main(argv: string[]): Promise<number> {
try {
await run(argv);
return 0;
} catch (err) {
if (err instanceof UsageError) {
console.error(err.message);
return 2;
}
console.error(`wcl: ${describeError(err)}`);
return 1;
}
}
process.exitCode = await main(process.argv.slice(2));Two design choices are worth noting.
runthrows andmaincatches. The work function has no knowledge of exit codes, and the singlecatchblock inmainis the only place that maps errors to numbers.- The
readFilecall has its own narrowtry/catch. Only the read is translated into a friendly message. A bug insidecountTextwould not be mislabeled as a file problem, and it would still reachmainand exit with 1.
Because the file uses top-level await, it needs "module": "NodeNext" and "type": "module", which you configured in earlier chapters.
process.exitCode versus process.exit
Node gives you two ways to set the code. They are not equivalent.
process.exit(1)ends the process immediately. Output still queued in stdout or stderr may be lost, especially when output goes to a pipe. Pending async work is abandoned.process.exitCode = 1only records the code. Node keeps running until the event loop is empty, flushes output, and then exits with that code.
This is also why main returns a number. A function that returns a code can be tested. A function that calls process.exit would end your test runner.
Writing the message to the right stream
Error text goes to stderr with console.error. Results go to stdout with console.log. The split matters when output is redirected:
wcl missing.txt > result.txtThe message wcl: missing.txt: no such file still appears in the terminal, and result.txt stays empty. If the error went to stdout, it would end up inside the file as if it were a result.
A consistent message format helps users and scripts. The pattern program: subject: reason is common, and it is what describeFsError produces.
Checking the behavior from the shell
Test the exit codes by hand after building. In bash, $? holds the code of the last command.
npm run build
node dist/cli.js notes.txt; echo "exit=$?"
node dist/cli.js nope.txt; echo "exit=$?"
node dist/cli.js; echo "exit=$?"
node dist/cli.js src; echo "exit=$?"Expected output, assuming notes.txt exists:
2 5 notes.txt
exit=0
wcl: nope.txt: no such file
exit=1
usage: wcl <file>
exit=2
wcl: src: is a directory
exit=1Common mistakes
- Catching and ignoring. An empty
catch {}hides failures and leaves the exit code at 0. Always report or rethrow. - Logging errors with
console.log. The message lands on stdout and pollutes piped output. - Forgetting to return a failure code. Printing an error and then falling through to
return 0is the most common bug in small tools. - Showing stack traces to users. A raw stack trace is useful for you and noise for them. Print
err.messagenormally. Consider printing the full error only when a debug flag or environment variable is set. - Assuming every thrown value is an
Error. Narrow withinstanceofbefore readingmessage. - Comparing
err.codeafter a cast. Casting toNodeJS.ErrnoExceptionworks, but narrowing with"code" in errkeeps the compiler honest.
What to carry forward
The structure here is the one the next chapter builds on. The pure function countText knows nothing about errors. run throws on problems. main turns those problems into messages and a number. The entry point assigns that number to process.exitCode. Each layer has one job, and the exit code is decided in exactly one place.
Exercise
Add a second usage error to wcl: if more than one file argument is given, print "usage: wcl <file>" to stderr and exit with code 2. Which function should throw the error, which function should turn it into an exit code, and why is returning 2 from main better than calling process.exit(2) there?
Show answer
Throw new UsageError("usage: wcl <file>") in run, right after the missing-file check, using the condition argv.length > 1. The catch block in main already maps UsageError to console.error(err.message) and return 2, so no further change is needed there. Returning 2 is better than process.exit(2) because the entry point assigns it to process.exitCode. Node then flushes any pending output before exiting, and main stays a normal function that a test can call and whose return value it can check.
Exercise
A user runs wcl data.txt | head -n 1 and the file is unreadable because of permissions. What appears on the terminal, what flows into the pipe, and what exit code does wcl itself return?
Show answer
The message "wcl: data.txt: permission denied" appears on the terminal, because it is written to stderr and the pipe only carries stdout. Nothing flows into the pipe, so head prints nothing. wcl returns exit code 1, because the failure is a runtime error and not a usage error. Note that in a plain shell pipeline, $? reports the exit code of the last command (head), not of wcl, unless you enable set -o pipefail.