How-To Guide

How to Implement CLI Error Handling and Exit Codes

Design CLI errors and exit codes: exit zero on success and non-zero on failure, keep stdout clean, and give the user a fixable message.

On this page

  1. Introduction
  2. Exit zero on success and non-zero on failure
  3. Separate stdout from stderr
  4. Write a message that names the fix
  5. Distinguish a user error from a bug
  6. Test the exit codes and the streams
  7. Common pitfalls
  8. Conclusion

Introduction

An exit code is the CLI’s verdict: zero means success and a non-zero means failure, and a script branches on it. A command that exits zero after failing breaks every script that checks the code, and a command that writes its errors to stdout corrupts every pipe that parses the output. The exit codes and the stream separation are the CLI’s contract with the script, and the error message is its contract with the person.

This tutorial covers the exit codes, the stream separation, a fixable error message, and the tests. The examples use a Node.js CLI, and the conventions apply to any command-line tool.

Exit zero on success and non-zero on failure

Set the exit code to zero when the command succeeded and to a non-zero value when it failed. The exit code is the machine-readable verdict, and a script’s if checks it. A command that fails but exits zero is a silent failure that propagates through a pipeline, and a command that succeeds but exits non-zero is a false alarm.

Use the convention: 1 for a general failure, 2 for a usage error, and a specific code for a specific failure where a script might branch, such as 3 for not-found. Document the codes, so a script can rely on them, and keep them stable across versions. Set the exit code as the last thing the command does, so no later code changes it.

async function main(argv) {
  const args = parse(argv);                     // a usage error exits 2
  if (args.help) { printHelp(); return 0; }
  try {
    await run(args);
    return 0;                                    // success
  } catch (err) {
    console.error('error: ' + err.message);      // the error to stderr
    return err.code === 'NOT_FOUND' ? 3 : 1;     // a specific or general failure
  }
}

main(process.argv.slice(2)).then((code) => process.exit(code));

Separate stdout from stderr

stdout is the command’s result, the thing a script pipes and parses, and stderr is the diagnostics, the thing a person reads. Write the result to stdout and the errors, the progress, and the logs to stderr, so a pipe carries only the result. A log line on stdout corrupts a parser, and a result on stderr is lost in a pipe.

This separation is what makes the command composable: the output can be piped to another tool or redirected to a file while the human still sees the diagnostics on the terminal. It is also how the progress is kept from corrupting the output, and how a --json output stays parseable. Keep stdout for the result, always.

Write a message that names the fix

An error message should say what failed and what to do: not error but error: config file not found at ./app.toml; run 'mycli init' to create one. The user should be able to act on the message without reading the code or the docs. Name the file, the value, or the command that fixes it, so the message is a next step, not a complaint.

Include the detail that helps: the path that was not found, the flag that was invalid, the expected value. Avoid a stack trace for a user error, which is noise; keep the trace for a bug, behind a verbose flag. Match the message to the audience: a user error gets a fix, an internal error gets a trace and a bug-report hint.

# a fixable error, on stderr, with a non-zero exit
$ mycli deploy
error: environment 'prod' not configured.
  Add it with: mycli env add prod --region us-east-1
$ echo $?
1

Distinguish a user error from a bug

A user error, such as a missing argument or a bad file, gets a clear message and a non-zero exit, without a stack trace. A bug, such as an unexpected exception, gets the message and, behind a verbose flag or an environment, the stack trace and a hint to report it. The distinction keeps the normal output clean and the debugging possible.

Catch the exceptions at the top level, so an unexpected one is handled rather than crashing with a raw trace. The top-level handler sets the exit code and writes the message, and, in verbose mode, the trace. An uncaught exception that prints a raw stack is a poor experience for a user, even though the exit code is non-zero.

Test the exit codes and the streams

Test the exit code for the success path and for each failure path, by running the command and asserting the code. Test that stdout carries only the result and stderr the diagnostics, by capturing both and asserting the separation. Test that a usage error exits 2 and prints a usage message, and that a not-found exits the documented code. These tests pin the contract with the script.

# exit code and stream separation
out=$(mycli list 2>/dev/null)      # stdout has the result only
mycli list >/dev/null 2>err.txt    # stderr has the diagnostics
echo "exit=$?" && cat err.txt
mycli --bad-flag; echo "usage-exit=$?"   # expect 2

Common pitfalls

Exiting zero after a failure so a script cannot detect it, writing the errors or the logs to stdout so a pipe is corrupted, an error message that does not say how to fix it, a raw stack trace for a user error, and a changing exit code that a script relied on are the recurring mistakes. A non-zero exit on failure, the stream separation, a fixable message, a user-versus-bug distinction, and stable documented codes address them.

Conclusion

A CLI’s exit code and streams are its contract with a script. Exit zero on success and non-zero on failure with specific codes, keep stdout to the result and stderr to the diagnostics, write a message that names the fix, and distinguish a user error from a bug. Self-check by asserting the exit code for success and each failure, and that a pipe carries only the result. Then a script can depend on the command’s outcome.

Sources: Unix: Exit status conventions, Node.js: process.exitCode, GNU Coding Standards: Exit status.

FAQ

Which exit code should I use?
0 for success, 1 for a general failure, and 2 for a usage error, which is the common convention. A specific code for a specific failure, such as 3 for a not-found, lets a script branch on it. Document the codes so the contract is clear.
Why keep stdout clean?
A script pipes stdout and parses it, so a stray log line on stdout corrupts the parse. The diagnostics go to stderr, which is for the human and for the terminal, and stdout is the machine-readable result. This separation is what makes the command composable.

Related Examples