chainerror/examples/tutorial13.rs

80 lines
2.3 KiB
Rust
Raw Normal View History

2019-03-04 11:38:11 +01:00
pub mod mycrate {
2020-08-28 16:45:24 +02:00
use chainerror::prelude::v1::*;
2019-03-04 11:38:11 +01:00
use std::io;
2020-03-03 14:37:11 +01:00
fn do_some_io() -> std::result::Result<(), Box<dyn std::error::Error + Send + Sync>> {
2019-03-04 11:38:11 +01:00
Err(io::Error::from(io::ErrorKind::NotFound))?;
Ok(())
}
2020-09-01 21:03:01 +02:00
derive_str_context!(Func2Error);
2019-03-04 11:38:11 +01:00
2020-03-03 14:37:11 +01:00
fn func2() -> std::result::Result<(), Box<dyn std::error::Error + Send + Sync>> {
2019-03-04 11:38:11 +01:00
let filename = "foo.txt";
2020-09-01 21:03:01 +02:00
do_some_io().context(Func2Error(format!("Error reading '{}'", filename)))?;
2019-03-04 11:38:11 +01:00
Ok(())
}
2019-03-13 11:34:53 +01:00
#[derive(Debug, Clone)]
2019-03-04 11:38:11 +01:00
pub enum ErrorKind {
Func2,
IO(String),
}
2019-03-07 16:50:16 +01:00
derive_err_kind!(Error, ErrorKind);
2019-03-04 11:38:11 +01:00
pub type Result<T> = std::result::Result<T, Error>;
2019-03-07 16:50:16 +01:00
impl std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> std::fmt::Result {
2019-03-04 11:38:11 +01:00
match self {
ErrorKind::Func2 => write!(f, "func1 error calling func2"),
ErrorKind::IO(filename) => write!(f, "Error reading '{}'", filename),
}
}
}
pub fn func1() -> Result<()> {
2020-09-01 21:03:01 +02:00
func2().context(ErrorKind::Func2)?;
2019-03-04 11:38:11 +01:00
let filename = String::from("bar.txt");
2020-09-01 21:03:01 +02:00
do_some_io().context(ErrorKind::IO(filename))?;
2019-03-04 11:38:11 +01:00
Ok(())
}
}
2020-03-03 14:37:11 +01:00
fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
2019-03-04 11:38:11 +01:00
use mycrate::func1;
use mycrate::ErrorKind;
use std::error::Error;
use std::io;
if let Err(e) = func1() {
match e.kind() {
ErrorKind::Func2 => eprintln!("Main Error Report: func1 error calling func2"),
ErrorKind::IO(ref filename) => {
eprintln!("Main Error Report: func1 error reading '{}'", filename)
}
}
eprintln!();
2020-03-03 14:37:11 +01:00
let mut s: &dyn Error = &e;
2019-03-04 11:38:11 +01:00
while let Some(c) = s.source() {
if let Some(ioerror) = c.downcast_ref::<io::Error>() {
eprintln!("caused by: std::io::Error: {}", ioerror);
match ioerror.kind() {
io::ErrorKind::NotFound => eprintln!("of kind: std::io::ErrorKind::NotFound"),
_ => {}
}
} else {
eprintln!("caused by: {}", c);
}
s = c;
}
eprintln!("\nDebug Error:\n{:?}", e);
2020-09-01 21:03:01 +02:00
std::process::exit(1);
2019-03-04 11:38:11 +01:00
}
Ok(())
}