clap_builder::error

Enum ErrorKind

Source
#[non_exhaustive]
pub enum ErrorKind {
Show 17 variants InvalidValue, UnknownArgument, InvalidSubcommand, NoEquals, ValueValidation, TooManyValues, TooFewValues, WrongNumberOfValues, ArgumentConflict, MissingRequiredArgument, MissingSubcommand, InvalidUtf8, DisplayHelp, DisplayHelpOnMissingArgumentOrSubcommand, DisplayVersion, Io, Format,
}
Expand description

Command line argument parser kind of error

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

InvalidValue

Occurs when an Arg has a set of possible values, and the user provides a value which isn’t in that set.

§Examples

let result = Command::new("prog")
    .arg(Arg::new("speed")
        .value_parser(["fast", "slow"]))
    .try_get_matches_from(vec!["prog", "other"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidValue);
§

UnknownArgument

Occurs when a user provides a flag, option, argument or subcommand which isn’t defined.

§Examples

let result = Command::new("prog")
    .arg(arg!(--flag "some flag"))
    .try_get_matches_from(vec!["prog", "--other"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::UnknownArgument);
§

InvalidSubcommand

Occurs when the user provides an unrecognized Subcommand which meets the threshold for being similar enough to an existing subcommand. If it doesn’t meet the threshold, or the ‘suggestions’ feature is disabled, the more general UnknownArgument error is returned.

§Examples

let result = Command::new("prog")
    .subcommand(Command::new("config")
        .about("Used for configuration")
        .arg(Arg::new("config_file")
            .help("The configuration file to use")))
    .try_get_matches_from(vec!["prog", "confi"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidSubcommand);
§

NoEquals

Occurs when the user doesn’t use equals for an option that requires equal sign to provide values.

let res = Command::new("prog")
    .arg(Arg::new("color")
         .action(ArgAction::Set)
         .require_equals(true)
         .long("color"))
    .try_get_matches_from(vec!["prog", "--color", "red"]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals);
§

ValueValidation

Occurs when the user provides a value for an argument with a custom validation and the value fails that validation.

§Examples

fn is_numeric(val: &str) -> Result<(), String> {
    match val.parse::<i64>() {
        Ok(..) => Ok(()),
        Err(..) => Err(String::from("value wasn't a number!")),
    }
}

let result = Command::new("prog")
    .arg(Arg::new("num")
         .value_parser(value_parser!(u8)))
    .try_get_matches_from(vec!["prog", "NotANumber"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::ValueValidation);
§

TooManyValues

Occurs when a user provides more values for an argument than were defined by setting Arg::num_args.

§Examples

let result = Command::new("prog")
    .arg(Arg::new("arg")
        .num_args(1..=2))
    .try_get_matches_from(vec!["prog", "too", "many", "values"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::TooManyValues);
§

TooFewValues

Occurs when the user provides fewer values for an argument than were defined by setting Arg::num_args.

§Examples

let result = Command::new("prog")
    .arg(Arg::new("some_opt")
        .long("opt")
        .num_args(3..))
    .try_get_matches_from(vec!["prog", "--opt", "too", "few"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::TooFewValues);
§

WrongNumberOfValues

Occurs when the user provides a different number of values for an argument than what’s been defined by setting Arg::num_args or than was implicitly set by Arg::value_names.

§Examples

let result = Command::new("prog")
    .arg(Arg::new("some_opt")
        .long("opt")
        .action(ArgAction::Set)
        .num_args(2))
    .try_get_matches_from(vec!["prog", "--opt", "wrong"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::WrongNumberOfValues);
§

ArgumentConflict

Occurs when the user provides two values which conflict with each other and can’t be used together.

§Examples

let result = Command::new("prog")
    .arg(Arg::new("debug")
        .long("debug")
        .action(ArgAction::SetTrue)
        .conflicts_with("color"))
    .arg(Arg::new("color")
        .long("color")
        .action(ArgAction::SetTrue))
    .try_get_matches_from(vec!["prog", "--debug", "--color"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::ArgumentConflict);
§

MissingRequiredArgument

Occurs when the user does not provide one or more required arguments.

§Examples

let result = Command::new("prog")
    .arg(Arg::new("debug")
        .required(true))
    .try_get_matches_from(vec!["prog"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
§

MissingSubcommand

Occurs when a subcommand is required (as defined by Command::subcommand_required), but the user does not provide one.

§Examples

let err = Command::new("prog")
    .subcommand_required(true)
    .subcommand(Command::new("test"))
    .try_get_matches_from(vec![
        "myprog",
    ]);
assert!(err.is_err());
assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand);
§

InvalidUtf8

Occurs when the user provides a value containing invalid UTF-8.

To allow arbitrary data

§Platform Specific

Non-Windows platforms only (such as Linux, Unix, OSX, etc.)

§Examples

let result = Command::new("prog")
    .arg(Arg::new("utf8")
        .short('u')
        .action(ArgAction::Set))
    .try_get_matches_from(vec![OsString::from("myprog"),
                                OsString::from("-u"),
                                OsString::from_vec(vec![0xE9])]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidUtf8);
§

DisplayHelp

Not a true “error” as it means --help or similar was used. The help message will be sent to stdout.

Note: If the help is displayed due to an error (such as missing subcommands) it will be sent to stderr instead of stdout.

§Examples

let result = Command::new("prog")
    .try_get_matches_from(vec!["prog", "--help"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelp);
§

DisplayHelpOnMissingArgumentOrSubcommand

Occurs when either an argument or a Subcommand is required, as defined by Command::arg_required_else_help , but the user did not provide one.

§Examples

let result = Command::new("prog")
    .arg_required_else_help(true)
    .subcommand(Command::new("config")
        .about("Used for configuration")
        .arg(Arg::new("config_file")
            .help("The configuration file to use")))
    .try_get_matches_from(vec!["prog"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand);
§

DisplayVersion

Not a true “error” as it means --version or similar was used. The message will be sent to stdout.

§Examples

let result = Command::new("prog")
    .version("3.0")
    .try_get_matches_from(vec!["prog", "--version"]);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayVersion);
§

Io

Represents an I/O error. Can occur when writing to stderr or stdout or reading a configuration file.

§

Format

Represents a Format error (which is a part of Display). Typically caused by writing to stderr or stdout.

Implementations§

Source§

impl ErrorKind

Source

pub fn as_str(self) -> Option<&'static str>

End-user description of the error case, where relevant

Trait Implementations§

Source§

impl Clone for ErrorKind

Source§

fn clone(&self) -> ErrorKind

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ErrorKind

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for ErrorKind

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Hash for ErrorKind

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for ErrorKind

Source§

fn eq(&self, other: &ErrorKind) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Copy for ErrorKind

Source§

impl Eq for ErrorKind

Source§

impl StructuralPartialEq for ErrorKind

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.

Layout§

Note: Most layout information is completely unstable and may even differ between compilations. The only exception is types with certain repr(...) attributes. Please see the Rust Reference's “Type Layout” chapter for details on type layout guarantees.

Size: 1 byte

Size for each variant:

  • InvalidValue: 0 bytes
  • UnknownArgument: 0 bytes
  • InvalidSubcommand: 0 bytes
  • NoEquals: 0 bytes
  • ValueValidation: 0 bytes
  • TooManyValues: 0 bytes
  • TooFewValues: 0 bytes
  • WrongNumberOfValues: 0 bytes
  • ArgumentConflict: 0 bytes
  • MissingRequiredArgument: 0 bytes
  • MissingSubcommand: 0 bytes
  • InvalidUtf8: 0 bytes
  • DisplayHelp: 0 bytes
  • DisplayHelpOnMissingArgumentOrSubcommand: 0 bytes
  • DisplayVersion: 0 bytes
  • Io: 0 bytes
  • Format: 0 bytes