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
use std::io::Write;
error_chain!{}
pub fn print_error(err: &Error, stream: &mut Write) {
let write_err_msg = "error writing to the given stream";
writeln!(stream, "error: {}", err).expect(write_err_msg);
for cause in err.iter().skip(1) {
writeln!(stream, " caused by: {}", cause).expect(write_err_msg);
}
if let Some(backtrace) = err.backtrace() {
writeln!(stream, "{:?}", backtrace).expect(write_err_msg);
}
}
#[cfg(test)]
mod tests {
use super::*;
use error::Error;
use error::ErrorKind;
#[test]
fn print_error_prints_error_to_given_stream() {
let err = Error::from_kind(ErrorKind::Msg("invalid key".to_string()));
let mut stream = Vec::new();
print_error(&err, &mut stream);
assert_eq!(String::from_utf8_lossy(&stream), "error: invalid key\n");
}
#[test]
fn print_error_includes_cause_when_present() {
let err = Error::with_chain(
Error::from_kind(ErrorKind::Msg("encoding error".to_string())),
ErrorKind::Msg("invalid key".to_string())
);
let mut stream = Vec::new();
print_error(&err, &mut stream);
assert_eq!(
String::from_utf8_lossy(&stream),
"error: invalid key\n caused by: encoding error\n"
);
}
}