Skip to content

Commit

Permalink
feat(Errors): Errors with custom description
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
vks authored and kbknapp committed Sep 5, 2016
1 parent 26d5207 commit 58512f2
Showing 1 changed file with 18 additions and 18 deletions.
36 changes: 18 additions & 18 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
}
}

0 comments on commit 58512f2

Please sign in to comment.