chainerror/examples/tutorial12.rs

78 lines
2.1 KiB
Rust
Raw Normal View History

use chainerror::Context as _;
2019-02-01 11:40:46 +01:00
use std::error::Error;
use std::io;
2020-03-03 14:37:11 +01:00
fn do_some_io() -> Result<(), Box<dyn Error + Send + Sync>> {
2019-02-01 11:40:46 +01:00
Err(io::Error::from(io::ErrorKind::NotFound))?;
Ok(())
}
chainerror::str_context!(Func2Error);
2019-02-01 11:40:46 +01:00
2020-03-03 14:37:11 +01:00
fn func2() -> Result<(), Box<dyn Error + Send + Sync>> {
2019-02-01 11:40:46 +01:00
let filename = "foo.txt";
2020-09-01 21:03:01 +02:00
do_some_io().context(Func2Error(format!("Error reading '{}'", filename)))?;
2019-02-01 11:40:46 +01:00
Ok(())
}
enum Func1ErrorKind {
Func2,
IO(String),
}
impl ::std::fmt::Display for Func1ErrorKind {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match self {
Func1ErrorKind::Func2 => write!(f, "func1 error calling func2"),
Func1ErrorKind::IO(filename) => write!(f, "Error reading '{}'", filename),
}
}
}
impl ::std::fmt::Debug for Func1ErrorKind {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", self)
}
}
impl ::std::error::Error for Func1ErrorKind {}
fn func1() -> chainerror::Result<(), Func1ErrorKind> {
2020-09-01 21:03:01 +02:00
func2().context(Func1ErrorKind::Func2)?;
2019-02-01 11:40:46 +01:00
let filename = String::from("bar.txt");
2020-09-01 21:03:01 +02:00
do_some_io().context(Func1ErrorKind::IO(filename))?;
2019-02-01 11:40:46 +01:00
Ok(())
}
2019-02-03 19:33:26 +01:00
fn handle_func1errorkind(e: &Func1ErrorKind) {
match e {
Func1ErrorKind::Func2 => eprintln!("Main Error Report: func1 error calling func2"),
Func1ErrorKind::IO(ref filename) => {
eprintln!("Main Error Report: func1 error reading '{}'", filename)
}
}
}
2020-03-03 14:37:11 +01:00
fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
2019-02-01 11:40:46 +01:00
if let Err(e) = func1() {
match *e {
Func1ErrorKind::Func2 => eprintln!("Main Error Report: func1 error calling func2"),
Func1ErrorKind::IO(ref filename) => {
eprintln!("Main Error Report: func1 error reading '{}'", filename)
}
}
2019-02-03 19:33:26 +01:00
handle_func1errorkind(&e);
2019-02-01 11:40:46 +01:00
if let Some(e) = e.find_chain_cause::<Func2Error>() {
eprintln!("\nError reported by Func2Error: {}", e)
}
eprintln!("\nDebug Error:\n{:?}", e);
2020-09-01 21:03:01 +02:00
std::process::exit(1);
2019-02-01 11:40:46 +01:00
}
Ok(())
}