use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub struct DisplayErrorContext<E: Error>(
pub E,
);
impl<E: Error> fmt::Display for DisplayErrorContext<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write_err(f, &self.0)?;
write!(f, " ({:?})", self.0)
}
}
fn write_err(f: &mut fmt::Formatter<'_>, err: &dyn Error) -> fmt::Result {
write!(f, "{err}")?;
if let Some(source) = err.source() {
write!(f, ": ")?;
write_err(f, source)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error;
use std::fmt;
#[derive(Debug)]
struct TestError {
what: &'static str,
source: Option<Box<dyn Error>>,
}
impl fmt::Display for TestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.what)
}
}
impl Error for TestError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref()
}
}
#[test]
fn no_sources() {
assert_eq!(
"test (TestError { what: \"test\", source: None })",
format!(
"{}",
DisplayErrorContext(TestError {
what: "test",
source: None
})
)
);
}
#[test]
fn sources() {
assert_eq!(
"foo: bar: baz (TestError { what: \"foo\", source: Some(TestError { what: \"bar\", source: Some(TestError { what: \"baz\", source: None }) }) })",
format!(
"{}",
DisplayErrorContext(TestError {
what: "foo",
source: Some(Box::new(TestError {
what: "bar",
source: Some(Box::new(TestError {
what: "baz",
source: None
}))
}) as Box<_>)
})
)
);
}
}