Skip to main content

capsid_protocol/
report.rs

1use std::{error::Error as StdError, fmt};
2
3const MAX_DEPTH: usize = 16;
4
5pub trait ErrorReport {
6    fn report(&self) -> Report<'_, Self>;
7}
8
9impl<E: StdError + ?Sized> ErrorReport for E {
10    fn report(&self) -> Report<'_, Self> {
11        Report(self)
12    }
13}
14
15pub struct Report<'a, E: ?Sized>(&'a E);
16
17impl<E: StdError + ?Sized> Report<'_, E> {
18    pub fn truncated(&self, max_chars: usize) -> String {
19        truncate(&self.to_string(), max_chars)
20    }
21}
22
23// Text that crosses a process or wire boundary is bounded by characters so the
24// cut never splits a UTF-8 sequence.
25pub fn truncate(text: &str, max_chars: usize) -> String {
26    text.chars().take(max_chars).collect()
27}
28
29impl<E: StdError + ?Sized> fmt::Display for Report<'_, E> {
30    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31        let mut previous = self.0.to_string();
32        formatter.write_str(&previous)?;
33        let mut source = self.0.source();
34        for _ in 0..MAX_DEPTH {
35            let Some(error) = source else {
36                break;
37            };
38            let text = error.to_string();
39            // Some errors print their source in their own message too.
40            let repeated = previous == text || previous.ends_with(&format!(": {text}"));
41            if !text.is_empty() && !repeated {
42                write!(formatter, ": {text}")?;
43            }
44
45            previous = text;
46            source = error.source();
47        }
48        Ok(())
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use std::io;
55
56    use super::*;
57
58    #[derive(Debug, thiserror::Error)]
59    #[error("outer")]
60    struct Outer(#[source] io::Error);
61
62    #[derive(Debug, thiserror::Error)]
63    #[error("middle")]
64    struct Middle(#[source] io::Error);
65
66    // no-slop-allow: no-source-in-error-display -- stands in for a third-party error that prints its source
67    #[derive(Debug, thiserror::Error)]
68    #[error("embedding: {0}")]
69    struct Embedding(#[source] io::Error);
70
71    #[test]
72    fn test_a_report_joins_each_cause() {
73        let error = Outer(io::Error::other(Middle(io::Error::other("leaf"))));
74        assert_eq!(error.report().to_string(), "outer: middle: leaf");
75    }
76
77    #[test]
78    fn test_a_report_prints_an_embedded_cause_once() {
79        let error = Outer(io::Error::other(Embedding(io::Error::other("leaf"))));
80        assert_eq!(error.report().to_string(), "outer: embedding: leaf");
81    }
82
83    #[test]
84    fn test_a_boxed_error_reports_its_chain() {
85        let error: Box<dyn StdError + Send + Sync> = Box::new(Outer(io::Error::other("leaf")));
86        assert_eq!(error.report().to_string(), "outer: leaf");
87    }
88}