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
#[derive(Clone, PartialEq, Eq, Debug)]
struct Error(pub String);
impl Error {
fn add_context(&self, context: &str) -> Error {
return format!("{}: {}", context, self).into();
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for Error {}
impl<T: Into<String>> From<T> for Error {
fn from(s: T) -> Self { Error(s.into()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_from_str() {
let error: Error = "this is a test error".into();
let err_display = format!("{}", error);
assert_eq!(err_display, "this is a test error");
}
#[test]
fn add_context() {
let err: Error = "this is a test error".into();
let with_context = err.add_context("some context");
let with_context_display = format!("{}", with_context);
assert_eq!(with_context_display, "some context: this is a test error");
}
}