Expand description
All utils return exit with an exit code. Usually, the following scheme is used:
0: succeeded1: minor problems2: major problems
This module provides types to reconcile these exit codes with idiomatic Rust error
handling. This has a couple advantages over manually using std::process::exit:
- It enables the use of
?,map_err,unwrap_or, etc. inuumain. - It encourages the use of
UResult/Resultin functions in the utils. - The error messages are largely standardized across utils.
- Standardized error messages can be created from external result types
(i.e.
std::io::Result&clap::ClapResult). set_exit_codetakes away the burden of manually tracking exit codes for non-fatal errors.
Usage
The signature of a typical util should be:
fn uumain(args: impl uucore::Args) -> UResult<()> {
...
}UResult is a simple wrapper around Result with a custom error trait: UError. The
most important difference with types implementing std::error::Error is that UErrors
can specify the exit code of the program when they are returned from uumain:
- When
Okis returned, the code set withset_exit_codeis used as exit code. Ifset_exit_codewas not used, then0is used. - When
Erris returned, the code corresponding with the error is used as exit code and the error message is displayed.
Additionally, the errors can be displayed manually with the [show] and [show_if_err] macros:
let res = Err(USimpleError::new(1, "Error!!"));
show_if_err!(res);
// or
if let Err(e) = res {
show!(e);
}Note: The [show] and [show_if_err] macros set the exit code of the program using
set_exit_code. See the documentation on that function for more information.
Guidelines
- Use error types from
uucorewhere possible. - Add error types to
uucoreif an error appears in multiple utils. - Prefer proper custom error types over
ExitCodeandUSimpleError. USimpleErrormay be used in small utils with simple error handling.- Using
ExitCodeis not recommended but can be useful for converting utils to useUResult.
Macros
- Shorthand to construct
UIoError-instances.
Structs
- A wrapper for
clap::Errorthat implementsUError - A special error type that does not print any message when returned from
uumain. Especially useful for porting utilities to usingUResult. - Wrapper type around
std::io::Error. - A simple error type with an exit code and a message that implements
UError.
Traits
- Extension trait for
clap::Errorto adjust the exit code. - Custom errors defined by the utils and
uucore.
Functions
- Get the last exit code set with
set_exit_code. The default value is0. - Set the exit code for the program if
uumainreturnsOk(()). - Strip the trailing “ (os error XX)“ from io error strings.
Type Definitions
- Result type that should be returned by all utils.