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
/Result
in 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_code
takes 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 UError
s
can specify the exit code of the program when they are returned from uumain
:
- When
Ok
is returned, the code set withset_exit_code
is used as exit code. Ifset_exit_code
was not used, then0
is used. - When
Err
is 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
uucore
where possible. - Add error types to
uucore
if an error appears in multiple utils. - Prefer proper custom error types over
ExitCode
andUSimpleError
. USimpleError
may be used in small utils with simple error handling.- Using
ExitCode
is not recommended but can be useful for converting utils to useUResult
.
Macros
Structs
A wrapper for clap::Error
that implements UError
A special error type that does not print any message when returned from
uumain
. Especially useful for porting utilities to using UResult
.
Wrapper type around std::io::Error
.
A simple error type with an exit code and a message that implements UError
.
Traits
Enables the conversion from std::io::Error
to UError
and from std::io::Result
to
UResult
.
Extension trait for clap::Error
to 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 is 0
.
Set the exit code for the program if uumain
returns Ok(())
.
Strip the trailing “ (os error XX)“ from io error strings.
Type Definitions
Result type that should be returned by all utils.