failure_tools/
lib.rs

1extern crate failure;
2
3use std::{process, io::{stderr, stdout, Write}};
4use failure::Error;
5
6/// Given an `Error`, print all the causes to `w`
7pub fn print_causes(e: impl Into<Error>, mut w: impl Write) {
8    let e = e.into();
9    let causes = e.causes().collect::<Vec<_>>();
10    let num_causes = causes.len();
11    for (index, cause) in causes.iter().enumerate() {
12        if index == 0 {
13            writeln!(w, "{}", cause).ok();
14            if num_causes > 1 {
15                writeln!(w, "Caused by: ").ok();
16            }
17        } else {
18            writeln!(w, " {}: {}", num_causes - index, cause).ok();
19        }
20    }
21}
22
23/// If the `Result` is `Ok(v)`, return `v`. Otherwise `print_causes()`
24/// and exit with exit code 1.
25pub fn ok_or_exit<T, E>(r: Result<T, E>) -> T
26where
27    E: Into<Error>,
28{
29    match r {
30        Ok(r) => r,
31        Err(e) => {
32            stdout().flush().ok();
33            write!(stderr(), "error: ").ok();
34            print_causes(e, stderr());
35            process::exit(1);
36        }
37    }
38}