Sub topic 12
Handling errors and exit codes
This chapter assumes you can write a derived Parser struct, read basic Result and Option types, and run a Cargo project from a terminal. You will separate two kinds of failure: errors clap reports for you, and errors your own program reports.
Two sources of errors
A command-line tool can fail in two places.
- Parse errors happen before your logic runs. The user gave a bad value, forgot a required argument, or used an unknown flag. clap detects these.
- Application errors happen inside your logic. The file does not exist, the network is down, or a value is valid for clap but wrong for your program.
Each kind needs a message on standard error (stderr) and a non-zero exit code. Shells, scripts, and CI systems read that code to decide whether the command worked.
Parse errors
Cli::parse() handles parse errors itself. It prints a message to stderr and exits the process with code 2. For --help and --version, it prints to stdout and exits with code 0. You write no code for this.
Take this program:
use clap::Parser;
use std::process::ExitCode;
#[derive(Parser)]
struct Cli {
/// How many items to process
n: u32,
}
fn run(cli: &Cli) -> Result<(), String> {
if cli.n == 0 {
return Err("n must be greater than zero".into());
}
println!("processing {} items", cli.n);
Ok(())
}
fn main() -> ExitCode {
let cli = Cli::parse();
match run(&cli) {
Ok(()) => ExitCode::SUCCESS,
Err(msg) => {
eprintln!("error: {msg}");
ExitCode::FAILURE
}
}
}If you pass abc as n, clap rejects it because abc is not a u32. Your run function never starts. If you pass 0, clap accepts it because 0 is a valid u32. Your own check in run rejects it.
| Input | Who reports it | Exit code |
|---|---|---|
| `abc` | clap | 2 |
| *(no argument)* | clap | 2 |
| `0` | your `run` function | 1 |
| `5` | nobody, it succeeds | 0 |
Application errors
run returns a Result. main converts the Err case into a message and an exit code. ExitCode::SUCCESS is 0 and ExitCode::FAILURE is 1. Use ExitCode::from(n) when you want specific codes, for example 3 for "file not found".
Write messages with eprintln!, not println!. Output on stdout can be piped into another program, and an error message in that stream corrupts the data.
Handling parse errors yourself
Sometimes you want to control what happens on a parse error, for example to log it first. Use try_parse(). It returns Result<Cli, clap::Error> instead of exiting.
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
n: u32,
}
fn main() {
match Cli::try_parse() {
Ok(cli) => println!("{cli:?}"),
Err(e) => {
// Prints the message, then exits with the right code
// (0 for --help and --version, 2 for real errors).
e.exit();
}
}
}e.exit() keeps clap's behavior. Use e.print() if you want to print the message but choose the exit code yourself.
Common mistakes
- Printing errors with
println!, which sends them to stdout. - Returning exit code 0 after printing an error, so scripts think the command succeeded.
- Re-checking things clap can already check. A range on a number belongs in
value_parser, not inrun. - Calling
std::process::exitdeep inside logic. It skips destructors and cannot be tested. Return anErrand exit inmain.
Exercise
A user runs your program with --port 99999, where port is declared as a u16. Which part of the program reports the error, what exit code results, and what stream receives the message?
Show answer
clap reports it during Cli::parse(), because 99999 does not fit in a u16. The message goes to stderr, the process exits with code 2, and run is never called.
Exercise
Change main in the first program so that a failure from run exits with code 3 instead of 1.
Show answer
Replace ExitCode::FAILURE with ExitCode::from(3). The Err(msg) arm becomes eprintln!("error: {msg}"); ExitCode::from(3).