1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
use std::{error::Error, io};
use super::Id;
pub fn format<W, E>(out: &mut W, error: E) -> Result<(), io::Error>
where
W: io::Write,
E: Error,
{
writeln!(out, "{error}")?;
format_sources(out, error)?;
Ok(())
}
pub fn format_with_id<W, E>(out: &mut W, id: &Id, error: E) -> Result<(), io::Error>
where
W: io::Write,
E: Error,
{
writeln!(out, "[{id}] {error}")?;
format_sources(out, error)?;
Ok(())
}
fn format_sources<W, E>(out: &mut W, error: E) -> Result<(), io::Error>
where
W: io::Write,
E: Error,
{
let mut sources = Sources::from(&error);
if let Some(source) = sources.next() {
writeln!(out)?;
writeln!(out, "Caused by:")?;
writeln!(out, " {source}")?;
for source in sources {
writeln!(out, " {source}")?;
}
writeln!(out)?;
}
Ok(())
}
struct Sources<'e> {
next: Option<&'e dyn Error>,
}
impl<'e, E> From<&'e E> for Sources<'e>
where
E: Error,
{
fn from(error: &'e E) -> Self {
Self {
next: error.source(),
}
}
}
// See also: <https://doc.rust-lang.org/std/error/trait.Error.html#method.sources> However, we only
// want to iterate the sources, and not the error itself. Personally, I find the `skip(1)`
// suggestion untidy, since the error itself is non-optional while the sources are optional.
impl<'a> Iterator for Sources<'a> {
type Item = &'a dyn Error;
fn next(&mut self) -> Option<Self::Item> {
let source = self.next;
self.next = self.next.and_then(|err| err.source());
source
}
}
|