2018-12-20 14:52:06 +01:00
|
|
|
use chainerror::*;
|
2018-12-20 10:08:54 +01:00
|
|
|
use std::error::Error;
|
|
|
|
use std::io;
|
|
|
|
use std::result::Result;
|
|
|
|
|
2020-03-03 14:37:11 +01:00
|
|
|
fn do_some_io() -> Result<(), Box<dyn Error + Send + Sync>> {
|
2018-12-20 10:08:54 +01:00
|
|
|
Err(io::Error::from(io::ErrorKind::NotFound))?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
derive_str_cherr!(Func2Error);
|
|
|
|
|
2020-03-03 14:37:11 +01:00
|
|
|
fn func2() -> Result<(), Box<dyn Error + Send + Sync>> {
|
2018-12-20 10:08:54 +01:00
|
|
|
let filename = "foo.txt";
|
|
|
|
do_some_io().map_err(mstrerr!(Func2Error, "Error reading '{}'", filename))?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2018-12-21 13:50:08 +01:00
|
|
|
enum Func1ErrorKind {
|
2018-12-20 10:08:54 +01:00
|
|
|
Func2,
|
|
|
|
IO(String),
|
|
|
|
}
|
|
|
|
|
2018-12-21 13:50:08 +01:00
|
|
|
impl ::std::fmt::Display for Func1ErrorKind {
|
2018-12-20 10:08:54 +01:00
|
|
|
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
|
|
|
|
match self {
|
2018-12-21 13:50:08 +01:00
|
|
|
Func1ErrorKind::Func2 => write!(f, "func1 error calling func2"),
|
|
|
|
Func1ErrorKind::IO(filename) => write!(f, "Error reading '{}'", filename),
|
2018-12-20 10:08:54 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-21 13:50:08 +01:00
|
|
|
impl ::std::fmt::Debug for Func1ErrorKind {
|
2018-12-20 10:08:54 +01:00
|
|
|
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
|
|
|
|
write!(f, "{}", self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-08 15:33:12 +01:00
|
|
|
impl ::std::error::Error for Func1ErrorKind {}
|
|
|
|
|
2018-12-21 13:50:08 +01:00
|
|
|
fn func1() -> ChainResult<(), Func1ErrorKind> {
|
|
|
|
func2().map_err(|e| cherr!(e, Func1ErrorKind::Func2))?;
|
2018-12-20 10:08:54 +01:00
|
|
|
let filename = String::from("bar.txt");
|
2018-12-21 13:50:08 +01:00
|
|
|
do_some_io().map_err(|e| cherr!(e, Func1ErrorKind::IO(filename)))?;
|
2018-12-20 10:08:54 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-03-03 14:37:11 +01:00
|
|
|
fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
|
2018-12-20 10:08:54 +01:00
|
|
|
if let Err(e) = func1() {
|
|
|
|
match e.kind() {
|
2018-12-21 13:50:08 +01:00
|
|
|
Func1ErrorKind::Func2 => eprintln!("Main Error Report: func1 error calling func2"),
|
|
|
|
Func1ErrorKind::IO(filename) => {
|
2018-12-20 10:08:54 +01:00
|
|
|
eprintln!("Main Error Report: func1 error reading '{}'", filename)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(e) = e.find_chain_cause::<Func2Error>() {
|
2018-12-21 13:50:08 +01:00
|
|
|
eprintln!("\nError reported by Func2Error: {}", e)
|
2018-12-20 10:08:54 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
eprintln!("\nDebug Error:\n{:?}", e);
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|