docopt

Enum Error

Source
pub enum Error {
    Usage(String),
    Argv(String),
    NoMatch,
    Deserialize(String),
    WithProgramUsage(Box<Error>, String),
    Help,
    Version(String),
}
Expand description

Represents the different types of Docopt errors.

This error type has a lot of variants. In the common case, you probably don’t care why Docopt has failed, and would rather just quit the program and show an error message instead. The exit method defined on the Error type will do just that. It will also set the exit code appropriately (no error for --help or --version, but an error code for bad usage, bad argv, no match or bad decode).

§Example

Generally, you want to parse the usage string, try to match the argv and then quit the program if there was an error reported at any point in that process. This can be achieved like so:

use docopt::Docopt;

const USAGE: &'static str = "
Usage: ...
";

let args = Docopt::new(USAGE)
                  .and_then(|d| d.parse())
                  .unwrap_or_else(|e| e.exit());

Variants§

§

Usage(String)

Parsing the usage string failed.

This error can only be triggered by the programmer, i.e., the writer of the Docopt usage string. This error is usually indicative of a bug in your program.

§

Argv(String)

Parsing the argv specified failed.

The payload is a string describing why the arguments provided could not be parsed.

This is distinct from NoMatch because it will catch errors like using flags that aren’t defined in the usage string.

§

NoMatch

The given argv parsed successfully, but it did not match any example usage of the program.

Regrettably, there is no descriptive message describing why the given argv didn’t match any of the usage strings.

§

Deserialize(String)

This indicates a problem deserializing a successful argv match into a deserializable value.

§

WithProgramUsage(Box<Error>, String)

Parsing failed, and the program usage should be printed next to the failure message. Typically this wraps Argv and NoMatch errors.

§

Help

Decoding or parsing failed because the command line specified that the help message should be printed.

§

Version(String)

Decoding or parsing failed because the command line specified that the version should be printed

The version is included as a payload to this variant.

Implementations§

Source§

impl Error

Source

pub fn fatal(&self) -> bool

Return whether this was a fatal error or not.

Non-fatal errors include requests to print the help or version information of a program, while fatal errors include those such as failing to decode or parse.

Source

pub fn exit(&self) -> !

Print this error and immediately exit the program.

If the error is non-fatal (e.g., Help or Version), then the error is printed to stdout and the exit status will be 0. Otherwise, when the error is fatal, the error is printed to stderr and the exit status will be 1.

Examples found in repository?
examples/cp.rs (line 24)
21
22
23
24
25
26
fn main() {
    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.deserialize())
        .unwrap_or_else(|e| e.exit());
    println!("{:?}", args);
}
More examples
Hide additional examples
examples/optional_command.rs (line 70)
67
68
69
70
71
72
fn main() {
    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.deserialize())
        .unwrap_or_else(|e| e.exit());
    println!("{:?}", args);
}
examples/verbose_multiple.rs (line 32)
29
30
31
32
33
34
fn main() {
    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.deserialize())
        .unwrap_or_else(|e| e.exit());
    println!("{:?}", args);
}
examples/cargo.rs (line 54)
51
52
53
54
55
56
fn main() {
    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.options_first(true).deserialize())
        .unwrap_or_else(|e| e.exit());
    println!("{:?}", args);
}
examples/decode.rs (line 37)
34
35
36
37
38
39
40
41
42
43
44
45
fn main() {
    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.deserialize())
        .unwrap_or_else(|e| e.exit());
    println!("{:?}", args);

    println!("\nSome values:");
    println!("  Speed: {}", args.flag_speed);
    println!("  Drifting? {}", args.flag_drifting);
    println!("  Names: {:?}", args.arg_name);
    println!("  Command 'ship' invoked? {:?}", args.cmd_ship);
}
examples/hashmap.rs (line 26)
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
fn main() {
    let version = "1.2.3".to_owned();
    let args = Docopt::new(USAGE)
                      .and_then(|dopt| dopt.version(Some(version)).parse())
                      .unwrap_or_else(|e| e.exit());
    println!("{:?}", args);

    // You can conveniently access values with `get_{bool,count,str,vec}`
    // functions. If the key doesn't exist (or if, e.g., you use `get_str` on
    // a switch), then a sensible default value is returned.
    println!("\nSome values:");
    println!("  Speed: {}", args.get_str("--speed"));
    println!("  Drifting? {}", args.get_bool("--drifting"));
    println!("  Names: {:?}", args.get_vec("<name>"));
    println!("  Command 'ship' invoked? {:?}", args.get_bool("ship"));
}

Trait Implementations§

Source§

impl Debug for Error

Source§

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

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

impl Display for Error

Source§

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

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

impl Error for Error

Source§

fn source(&self) -> Option<&(dyn StdError + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl Error for Error

Source§

fn custom<T: Display>(msg: T) -> Self

Raised when there is general error when deserializing a type. Read more
Source§

fn invalid_type(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self

Raised when a Deserialize receives a type different from what it was expecting. Read more
Source§

fn invalid_value(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self

Raised when a Deserialize receives a value of the right type but that is wrong for some other reason. Read more
Source§

fn invalid_length(len: usize, exp: &dyn Expected) -> Self

Raised when deserializing a sequence or map and the input data contains too many or too few elements. Read more
Source§

fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self

Raised when a Deserialize enum type received a variant with an unrecognized name.
Source§

fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self

Raised when a Deserialize struct type received a field with an unrecognized name.
Source§

fn missing_field(field: &'static str) -> Self

Raised when a Deserialize struct type expected to receive a required field with a particular name but that field was not present in the input.
Source§

fn duplicate_field(field: &'static str) -> Self

Raised when a Deserialize struct type received more than one of the same field.

Auto Trait Implementations§

§

impl Freeze for Error

§

impl RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl UnwindSafe for Error

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