Sub topic 12
Handling errors and exit codes
This chapter assumes you can define a derived Parser, read typed fields, and use Result and ? in Rust. It also assumes you know that a shell reads a program's exit status from $?. Here you will separate the errors clap reports from the errors your program reports. You will also choose exit codes and send each message to the right stream.
Two kinds of failure
A command-line tool can fail in two places.
- Parse errors happen before your code runs. The user gave an unknown flag, omitted a required argument, or typed
abcfor au32. Clap detects these. - Application errors happen after parsing succeeds. The file does not exist, the network is down, or nothing matched. Your code detects these.
Clap's default behavior for parse errors is already conventional. Cli::parse() prints a message to stderr and exits with status 2. The --help and --version requests also end the parse early, but they print to stdout and exit with status 0, because they are not failures.
Parse errors with `parse` and `try_parse`
Cli::parse() is a shortcut. It calls try_parse() and, on Err, calls Error::exit(). That method prints the message and ends the process immediately. Use try_parse() when you need to act before the process ends, such as logging, cleanup, or mapping to your own status.
use clap::Parser;
use std::process::ExitCode;
#[derive(Parser, Debug)]
struct Cli {
/// How many items to process
n: u32,
}
fn main() -> ExitCode {
let cli = match Cli::try_parse() {
Ok(cli) => cli,
Err(err) => {
// Prints to stdout for help/version, stderr otherwise.
let _ = err.print();
return ExitCode::from(err.exit_code() as u8);
}
};
println!("{cli:?}");
ExitCode::SUCCESS
}clap::Error also offers kind(), which returns an ErrorKind. Matching on ErrorKind::DisplayHelp or ErrorKind::DisplayVersion lets you tell a request for information apart from a mistake. exit_code() already does this: it returns 0 for those two kinds and 2 for everything else.
Application errors
Keep failure handling in one place. Put the logic in a function that returns Result, and let main turn the result into an exit status and a message. Returning ExitCode from main makes this explicit.
use clap::Parser;
use std::fmt;
use std::fs;
use std::io;
use std::path::PathBuf;
use std::process::ExitCode;
/// Print lines of a file that contain a pattern.
#[derive(Parser)]
struct Cli {
/// File to search
path: PathBuf,
/// Only print lines containing this text
#[arg(short, long)]
filter: Option<String>,
}
enum AppError {
Read { path: PathBuf, source: io::Error },
NoMatch,
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AppError::Read { path, source } => {
write!(f, "cannot read {}: {source}", path.display())
}
AppError::NoMatch => write!(f, "no matching lines"),
}
}
}
impl AppError {
fn exit_code(&self) -> ExitCode {
match self {
AppError::Read { .. } => ExitCode::from(66),
AppError::NoMatch => ExitCode::from(1),
}
}
}
fn run(cli: &Cli) -> Result<(), AppError> {
let text = fs::read_to_string(&cli.path).map_err(|source| AppError::Read {
path: cli.path.clone(),
source,
})?;
let mut found = false;
for line in text.lines() {
if cli.filter.as_deref().map_or(true, |f| line.contains(f)) {
println!("{line}");
found = true;
}
}
if found {
Ok(())
} else {
Err(AppError::NoMatch)
}
}
fn main() -> ExitCode {
let cli = Cli::parse();
match run(&cli) {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
eprintln!("error: {err}");
err.exit_code()
}
}
}Three habits matter here.
- Messages go to stderr with
eprintln!. Stdout carries the program's output, which another program may be reading through a pipe. An error mixed into it corrupts the data. - The
error:prefix matches clap's style. Users then see one consistent format. runnever callsstd::process::exit. It returns an error, so the logic stays testable and destructors still run.
Returning `Result` from `main`
Rust also allows fn main() -> Result<(), E> where E: Debug. On Err, the runtime prints Error: followed by the Debug form of the error to stderr and exits with status 1. This is short, but the Debug output of an io::Error looks like Os { code: 2, kind: NotFound, message: "No such file or directory" }. That is poor for end users, and you cannot choose the status. It is acceptable for quick scripts. For tools other people run, use the ExitCode pattern above.
Choosing exit codes
Status 0 means success and anything else means failure. Shells and scripts rarely need more than that, but a few conventions help.
| Code | Meaning | Source |
|---|---|---|
| 0 | Success | Universal |
| 1 | General failure | Universal convention |
| 2 | Command-line usage error | Clap's choice for parse errors |
| 64 | Usage error (`EX_USAGE`) | BSD `sysexits.h`, optional |
| 66 | Input file missing or unreadable (`EX_NOINPUT`) | BSD `sysexits.h`, optional |
| 101 | Rust panic | Rust runtime |
Pick a small set, document it in your --help text or README, and keep it stable. Avoid reusing 2 for an application failure. A script that checks for 2 expects it to mean a bad invocation. Codes above 255 do not exist: the operating system keeps only the low 8 bits, which is why ExitCode::from takes a u8.
Some tools give status 1 a specific meaning. The grep command exits 1 when nothing matched and 2 on real errors. The example above mirrors the first part of that convention.
Errors in value parsing
When a custom value_parser function returns Err(String), clap wraps the message in its standard format and exits with status 2. You get consistent output with no extra code.
use clap::Parser;
fn parse_percent(s: &str) -> Result<u8, String> {
let n: u8 = s
.parse()
.map_err(|_| format!("`{s}` is not a whole number from 0 to 100"))?;
if n > 100 {
return Err(format!("{n} is greater than 100"));
}
Ok(n)
}
#[derive(Parser, Debug)]
struct Cli {
/// Output quality in percent
#[arg(long, value_parser = parse_percent)]
quality: u8,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}Running it with --quality 150 prints roughly the following to stderr and exits with status 2:
error: invalid value '150' for '--quality <QUALITY>': 150 is greater than 100
For more information, try '--help'.Put per-value checks in the parser. Failures there carry the argument name and are reported before any of your logic runs.
Validating across arguments
Some rules involve several fields, such as --start not exceeding --end. A parser for one value cannot see the other. You can check after parsing and still report the problem in clap's style by building the error from the command definition:
use clap::{error::ErrorKind, CommandFactory, Parser};
#[derive(Parser)]
struct Cli {
#[arg(long)]
start: u32,
#[arg(long)]
end: u32,
}
fn main() {
let cli = Cli::parse();
if cli.start > cli.end {
Cli::command()
.error(
ErrorKind::ValueValidation,
"--start must not be greater than --end",
)
.exit();
}
println!("range {}..{}", cli.start, cli.end);
}The user sees the same formatted message and the same status 2 as for any other usage error. Reserve this for real usage mistakes. Failures that depend on the environment, such as a missing file, belong in the application error path.
Common mistakes
- Using
unwrap()orexpect()on user-influenced values. A failure becomes a panic message with a backtrace hint and exit status 101. - Printing errors with
println!. The message lands on stdout and breaks pipelines. - Calling
process::exitdeep inside helper functions. This skips cleanup and makes the code hard to test. - Ignoring write failures.
println!panics if stdout is closed, for example inmytool | head -n 1. Tools that expect to feed pipes can write withwriteln!to a locked stdout and handle theBrokenPipeerror kind.
Exercise
A tool built with the ExitCode pattern above runs as mytool data.txt --filter zzz. The file exists but no line contains zzz. What is printed, to which stream, and what is the exit status? What changes if the file does not exist?
Show answer
When no line matches, run returns AppError::NoMatch. main prints error: no matching lines to stderr, and the exit status is 1. Nothing is printed to stdout. If the file does not exist, fs::read_to_string fails and run returns AppError::Read. main prints error: cannot read data.txt: ... to stderr, followed by the operating system's message, and exits with status 66. Neither case involves clap, because parsing succeeded.
Exercise
Why should parse_percent return Err(String) instead of calling std::process::exit(2) itself?
Show answer
Returning Err lets clap add the argument name, format the message like its other errors, print the usage hint, and exit with its standard status. It also keeps the function pure, so a test can call parse_percent("150") or Cli::try_parse_from and inspect the error without ending the test process.