macro_rules! err_kind {
($e:ident, $k:ident) => { ... };
}Expand description
Derive an Error for an ErrorKind, which wraps a Error and implements a kind() method
It basically hides Error to the outside and only exposes the kind()
method.
Error::kind() returns the ErrorKind Error::source() returns the parent error
ยงExamples
use chainerror::Context as _;
use std::io;
fn do_some_io(_f: &str) -> std::result::Result<(), io::Error> {
return Err(io::Error::from(io::ErrorKind::NotFound));
}
#[derive(Debug, Clone)]
pub enum ErrorKind {
IO(String),
FatalError(String),
Unknown,
}
chainerror::err_kind!(Error, ErrorKind);
impl std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> std::fmt::Result {
match self {
ErrorKind::FatalError(e) => write!(f, "fatal error {}", e),
ErrorKind::Unknown => write!(f, "unknown error"),
ErrorKind::IO(filename) => write!(f, "Error reading '{}'", filename),
}
}
}
impl ErrorKind {
fn from_io_error(e: &io::Error, f: String) -> Self {
match e.kind() {
io::ErrorKind::BrokenPipe => panic!("Should not happen"),
io::ErrorKind::ConnectionReset => {
ErrorKind::FatalError(format!("While reading `{}`: {}", f, e))
}
_ => ErrorKind::IO(f),
}
}
}
impl From<&io::Error> for ErrorKind {
fn from(e: &io::Error) -> Self {
ErrorKind::IO(format!("{}", e))
}
}
pub fn func1() -> std::result::Result<(), Error> {
let filename = "bar.txt";
do_some_io(filename).map_context(|e| ErrorKind::from_io_error(e, filename.into()))?;
do_some_io(filename).map_context(|e| ErrorKind::IO(filename.into()))?;
do_some_io(filename).map_context(|e| ErrorKind::from(e))?;
Ok(())
}