chainerror/examples/example.rs

75 lines
2 KiB
Rust
Raw Normal View History

2018-12-21 13:50:08 +01:00
use std::error::Error;
use std::io;
use std::result::Result;
2020-08-28 16:45:24 +02:00
use chainerror::prelude::v1::*;
2019-03-13 11:34:53 +01:00
2020-03-03 14:37:11 +01:00
fn do_some_io() -> Result<(), Box<dyn Error + Send + Sync>> {
2018-12-21 13:50:08 +01:00
Err(io::Error::from(io::ErrorKind::NotFound))?;
Ok(())
}
2020-03-03 14:37:11 +01:00
fn func3() -> Result<(), Box<dyn Error + Send + Sync>> {
2018-12-21 13:50:08 +01:00
let filename = "foo.txt";
2020-08-28 16:45:24 +02:00
do_some_io().cherr(format!("Error reading '{}'", filename))?;
2018-12-21 13:50:08 +01:00
Ok(())
}
derive_str_cherr!(Func2Error);
fn func2() -> ChainResult<(), Func2Error> {
2020-08-28 16:45:24 +02:00
func3().cherr(Func2Error(format!("func2 error: calling func3")))?;
2018-12-21 13:50:08 +01:00
Ok(())
}
enum Func1Error {
Func2,
IO(String),
}
impl ::std::fmt::Display for Func1Error {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match self {
Func1Error::Func2 => write!(f, "func1 error calling func2"),
Func1Error::IO(filename) => write!(f, "Error reading '{}'", filename),
}
}
}
impl ::std::fmt::Debug for Func1Error {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", self)
}
}
fn func1() -> ChainResult<(), Func1Error> {
2020-08-28 16:45:24 +02:00
func2().cherr(Func1Error::Func2)?;
2018-12-21 13:50:08 +01:00
let filename = String::from("bar.txt");
2020-08-28 16:45:24 +02:00
do_some_io().cherr(Func1Error::IO(filename))?;
2018-12-21 13:50:08 +01:00
Ok(())
}
fn main() {
if let Err(e) = func1() {
match e.kind() {
Func1Error::Func2 => eprintln!("Main Error Report: func1 error calling func2"),
Func1Error::IO(filename) => {
eprintln!("Main Error Report: func1 error reading '{}'", filename)
}
}
if let Some(e) = e.find_chain_cause::<Func2Error>() {
eprintln!("\nError reported by Func2Error: {}", e)
}
if let Some(e) = e.root_cause() {
let ioerror = e.downcast_ref::<io::Error>().unwrap();
eprintln!("\nThe root cause was: std::io::Error: {:#?}", ioerror);
}
eprintln!("\nDebug Error:\n{:?}", e);
2020-08-28 16:45:24 +02:00
eprintln!("\nAlternative Debug Error:\n{:#?}", e);
2018-12-21 13:50:08 +01:00
}
}