ts_error/
report.rs

1use alloc::boxed::Box;
2use core::{error::Error, fmt};
3
4use ts_ansi::style::{BOLD, DEFAULT, RED, RESET};
5
6/// An error report, displays the error stack of some error.
7pub struct Report<'e> {
8    /// The error for this report.
9    pub source: Box<dyn Error + 'e>,
10}
11impl<'e> Report<'e> {
12    /// Create a new error report.
13    pub fn new<E: Error + 'e>(source: E) -> Self {
14        Self {
15            source: Box::new(source),
16        }
17    }
18}
19impl Error for Report<'static> {
20    fn source(&self) -> Option<&(dyn Error + 'static)> {
21        Some(self.source.as_ref())
22    }
23}
24impl fmt::Debug for Report<'_> {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        write!(f, "{self}")
27    }
28}
29impl fmt::Display for Report<'_> {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        let mut current_error = Some(self.source.as_ref());
32        let mut count = 1;
33
34        while let Some(error) = current_error {
35            writeln!(f, " {BOLD}{RED}{count}{DEFAULT}.{RESET} {error}")?;
36
37            count += 1;
38            current_error = error.source();
39        }
40
41        Ok(())
42    }
43}