Module uucore::error

source ·
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 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 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 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 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.

Macros

Structs

Traits

Functions

Type Definitions

  • Result type that should be returned by all utils.