Module uucore::error[][src]

Expand description

All utils return exit with an exit code. Usually, the following scheme is used:

  • 0: succeeded
  • 1: minor problems
  • 2: 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:

  1. It enables the use of ?, map_err, unwrap_or, etc. in uumain.
  2. It encourages the use of UResult/Result in functions in the utils.
  3. The error messages are largely standardized across utils.
  4. Standardized error messages can be created from external result types (i.e. std::io::Result & clap::ClapResult).
  5. 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 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 Ok is returned, the code set with set_exit_code is used as exit code. If set_exit_code was not used, then 0 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 common errors where possible.
  • Add variants to UCommonError if an error appears in multiple utils.
  • Prefer proper custom error types over ExitCode and USimpleError.
  • USimpleError may be used in small utils with simple error handling.
  • Using ExitCode is not recommended but can be useful for converting utils to use UResult.

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

Common errors for utilities.

The error type of UResult.

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.