chainerror/examples/tutorial11.rs

67 lines
1.8 KiB
Rust
Raw Normal View History

use chainerror::Context as _;
2018-12-20 10:08:54 +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>> {
2018-12-20 10:08:54 +01:00
Err(io::Error::from(io::ErrorKind::NotFound))?;
Ok(())
}
chainerror::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(())
}
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)
}
}
impl ::std::error::Error for Func1ErrorKind {}
fn func1() -> chainerror::Result<(), Func1ErrorKind> {
2020-09-01 21:03:01 +02:00
func2().context(Func1ErrorKind::Func2)?;
2018-12-20 10:08:54 +01:00
let filename = String::from("bar.txt");
2020-09-01 21:03:01 +02:00
do_some_io().context(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);
2020-09-01 21:03:01 +02:00
std::process::exit(1);
2018-12-20 10:08:54 +01:00
}
Ok(())
}