Module uucore::error [−][src]
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 type: 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 common errors where possible.
- Add variants to
UCommonErrorif 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.
Structs
A special error type that does not print any message when returned from
uumain. Especially useful for porting utilities to using UResult.
A UCommonError with an overridden exit code.
Wrapper type around std::io::Error.
A simple error type with an exit code and a message that implements UCustomError.
Enums
Traits
Enables the conversion from std::io::Error to UError and from std::io::Result to
UResult.
Custom errors defined by the utils.
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(()).
Type Definitions
Should be returned by all utils.