Skip to main content

criner_cli/
error.rs

1use std::{error::Error, fmt, process};
2
3struct WithCauses<'a>(&'a dyn Error);
4
5impl<'a> fmt::Display for WithCauses<'a> {
6    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7        write!(f, "ERROR: {}", self.0)?;
8        let mut cursor = self.0;
9        while let Some(err) = cursor.source() {
10            write!(f, "\ncaused by: \n{}", err)?;
11            cursor = err;
12        }
13        writeln!(f)
14    }
15}
16
17pub fn ok_or_exit<T, E>(result: Result<T, E>) -> T
18where
19    E: Error,
20{
21    match result {
22        Ok(v) => v,
23        Err(err) => {
24            println!("{}", WithCauses(&err));
25            process::exit(2);
26        }
27    }
28}