etk_cli/
errors.rs

1//! Utilities for printing errors.
2
3use snafu::{Backtrace, ErrorCompat};
4
5use std::fmt;
6
7/// A wrapper which prints a [`snafu::ErrorCompat`], plus its backtraces if they
8/// exist.
9#[derive(Debug)]
10pub struct WithSources<E>(pub E);
11
12impl<E> fmt::Display for WithSources<E>
13where
14    E: ErrorCompat + std::error::Error,
15{
16    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
17        writeln!(f, "Error: {}", self.0)?;
18
19        let mut current = self.0.source();
20
21        while let Some(e) = current.take() {
22            writeln!(f, "Caused by: {}", e)?;
23            current = e.source();
24        }
25
26        if let Some(backtrace) = ErrorCompat::backtrace(&self.0) {
27            // XXX: hack to determine if snafu's backtraces are enabled.
28            if std::mem::size_of::<Backtrace>() > 0 {
29                writeln!(f, "Backtrace:\n{}", backtrace)?;
30            }
31        }
32
33        Ok(())
34    }
35}