2020-08-28 16:45:24 +02:00
|
|
|
use chainerror::prelude::v1::*;
|
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(())
|
|
|
|
}
|
|
|
|
|
2020-09-01 21:03:01 +02:00
|
|
|
derive_str_context!(Func2Error);
|
2018-12-20 10:08:54 +01:00
|
|
|
|
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";
|
2020-09-01 21:03:01 +02:00
|
|
|
do_some_io().context(Func2Error(format!("Error reading '{}'", filename)))?;
|
2018-12-20 10:08:54 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-09-01 21:03:01 +02:00
|
|
|
derive_str_context!(Func1Error);
|
2018-12-20 10:08:54 +01:00
|
|
|
|
2020-03-03 14:37:11 +01:00
|
|
|
fn func1() -> Result<(), Box<dyn Error + Send + Sync>> {
|
2020-09-01 21:03:01 +02:00
|
|
|
func2().context(Func1Error(format!("func1 error")))?;
|
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() {
|
|
|
|
if let Some(f1err) = e.downcast_chain_ref::<Func1Error>() {
|
|
|
|
eprintln!("Func1Error: {}", f1err);
|
|
|
|
|
|
|
|
if let Some(f2err) = f1err.find_cause::<ChainError<Func2Error>>() {
|
|
|
|
eprintln!("Func2Error: {}", f2err);
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(f2err) = f1err.find_chain_cause::<Func2Error>() {
|
|
|
|
eprintln!("Debug Func2Error:\n{:?}", f2err);
|
|
|
|
}
|
|
|
|
}
|
2020-09-01 21:03:01 +02:00
|
|
|
std::process::exit(1);
|
2018-12-20 10:08:54 +01:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|