mirror of
https://github.com/clap-rs/clap
synced 2024-11-10 14:54:15 +00:00
feat(Errors): Errors with custom description
This is useful if a more meaningful message can be displayed to the user with `Error::exit`. For example, if a file is not found, the converted `io::Error` will give a message like: "error: entity not found" With this, it is possible to replace this message with a more useful one, like for instance: "error: configuration file not found" Coloring is respected. Some duplication in the `From::from` impls was reduced.
This commit is contained in:
parent
26d5207728
commit
58512f2fcb
1 changed files with 18 additions and 18 deletions
|
@ -788,6 +788,22 @@ impl Error {
|
|||
info: Some(vec![a]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an error with a custom description.
|
||||
///
|
||||
/// This can be used in combination with `Error::exit` to exit your program
|
||||
/// with a custom error message.
|
||||
pub fn with_description(description: &str, kind: ErrorKind) -> Self {
|
||||
let c = fmt::Colorizer {
|
||||
use_stderr: true,
|
||||
when: fmt::ColorWhen::Auto
|
||||
};
|
||||
Error {
|
||||
message: format!("{} {}", c.error("error:"), description),
|
||||
kind: kind,
|
||||
info: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StdError for Error {
|
||||
|
@ -804,28 +820,12 @@ impl Display for Error {
|
|||
|
||||
impl From<io::Error> for Error {
|
||||
fn from(e: io::Error) -> Self {
|
||||
let c = fmt::Colorizer {
|
||||
use_stderr: true,
|
||||
when: fmt::ColorWhen::Auto
|
||||
};
|
||||
Error {
|
||||
message: format!("{} {}", c.error("error:"), e.description()),
|
||||
kind: ErrorKind::Io,
|
||||
info: None,
|
||||
}
|
||||
Error::with_description(e.description(), ErrorKind::Io)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std_fmt::Error> for Error {
|
||||
fn from(e: std_fmt::Error) -> Self {
|
||||
let c = fmt::Colorizer {
|
||||
use_stderr: true,
|
||||
when: fmt::ColorWhen::Auto
|
||||
};
|
||||
Error {
|
||||
message: format!("{} {}", c.error("error:"), e),
|
||||
kind: ErrorKind::Format,
|
||||
info: None,
|
||||
}
|
||||
Error::with_description(e.description(), ErrorKind::Format)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue