Skip to content

Commit b826f4f

Browse files
committed
Book: Draft for exit code chapter
Resolves rust-cli#39
1 parent 3be510f commit b826f4f

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

src/in-depth/exit-code.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,55 @@
11
# Exit codes
2+
3+
A program doesn't always success.
4+
And when an error occurs,
5+
you should make sure to use the correct ways to emit the necessary information.
6+
In addition to
7+
[telling the user about errors](human-communication.md),
8+
on most systems,
9+
when a process exits,
10+
it also emits an exit code
11+
(an integer between 0 and 255).
12+
You should try to emit the correct code
13+
for your program's state.
14+
For example,
15+
in the ideal case when your program succeeded,
16+
it should exit with `0`.
17+
18+
When an error ocurred, it gets a bit more complicated, though.
19+
In the wild,
20+
a lot of tools exit with `1` when a general failure ocurred.
21+
Currently, Rust set and exit code of `101` when the process panicked.
22+
Beyond that, many people have done many things in their programs.
23+
24+
So, what to do?
25+
The BSD ecosystem has collected a common definition for their exit codes
26+
in a system-provided header file called [`sysexits.h`]
27+
The Rust library [`exitcode`] provides these same codes
28+
ready to be used in your application.
29+
Please see it's API documentation for the possible values to use.
30+
31+
One way to use it is like this:
32+
33+
```rust
34+
fn main() {
35+
// ...actual work...
36+
match result {
37+
Ok(_) => {
38+
println!("Done!");
39+
std::process::exit(exitcode::OK);
40+
}
41+
Err(CustomError::CantReadConfig(e)) => {
42+
eprintln!("Error: {}", e);
43+
std::process::exit(exitcode::CONFIG);
44+
}
45+
Err(e) => {
46+
eprintln!("Error: {}", e);
47+
std::process::exit(exitcode::DATAERR);
48+
}
49+
}
50+
}
51+
```
52+
53+
54+
[`exitcode`]: https://crates.io/crates/exitcode
55+
[`sysexits.h`]: https://www.freebsd.org/cgi/man.cgi?query=sysexits&apropos=0&sektion=0&manpath=FreeBSD+11.2-stable&arch=default&format=html

0 commit comments

Comments
 (0)