use std::{error::Error as StdError, fmt};
const MAX_DEPTH: usize = 16;
pub trait ErrorReport {
fn report(&self) -> Report<'_, Self>;
}
impl<E: StdError + ?Sized> ErrorReport for E {
fn report(&self) -> Report<'_, Self> {
Report(self)
}
}
pub struct Report<'a, E: ?Sized>(&'a E);
impl<E: StdError + ?Sized> Report<'_, E> {
pub fn truncated(&self, max_chars: usize) -> String {
truncate(&self.to_string(), max_chars)
}
}
pub fn truncate(text: &str, max_chars: usize) -> String {
text.chars().take(max_chars).collect()
}
impl<E: StdError + ?Sized> fmt::Display for Report<'_, E> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut previous = self.0.to_string();
formatter.write_str(&previous)?;
let mut source = self.0.source();
for _ in 0..MAX_DEPTH {
let Some(error) = source else {
break;
};
let text = error.to_string();
let repeated = previous == text || previous.ends_with(&format!(": {text}"));
if !text.is_empty() && !repeated {
write!(formatter, ": {text}")?;
}
previous = text;
source = error.source();
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::io;
use super::*;
#[derive(Debug, thiserror::Error)]
#[error("outer")]
struct Outer(#[source] io::Error);
#[derive(Debug, thiserror::Error)]
#[error("middle")]
struct Middle(#[source] io::Error);
#[derive(Debug, thiserror::Error)]
#[error("embedding: {0}")]
struct Embedding(#[source] io::Error);
#[test]
fn test_a_report_joins_each_cause() {
let error = Outer(io::Error::other(Middle(io::Error::other("leaf"))));
assert_eq!(error.report().to_string(), "outer: middle: leaf");
}
#[test]
fn test_a_report_prints_an_embedded_cause_once() {
let error = Outer(io::Error::other(Embedding(io::Error::other("leaf"))));
assert_eq!(error.report().to_string(), "outer: embedding: leaf");
}
#[test]
fn test_a_boxed_error_reports_its_chain() {
let error: Box<dyn StdError + Send + Sync> = Box::new(Outer(io::Error::other("leaf")));
assert_eq!(error.report().to_string(), "outer: leaf");
}
}