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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use std::{error::Error as StdError, fmt};
#[derive(Debug, PartialEq)]
pub struct Error {
description: String,
}
impl Error {
pub fn new<T: Into<String>>(description: T) -> Error {
Error {
description: description.into(),
}
}
pub fn from_cause<T: StdError>(cause: T) -> Error {
Error {
description: format!("{}", cause),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description)
}
}
impl StdError for Error {}
impl From<&str> for Error {
fn from(cause: &str) -> Error {
Error::new(cause)
}
}
impl From<String> for Error {
fn from(cause: String) -> Error {
Error::new(cause)
}
}
macro_rules! from_other_error {
($type:path) => {
impl From<$type> for Error {
fn from(cause: $type) -> Error {
Error::from_cause(cause)
}
}
};
}
from_other_error!(::std::io::Error);
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new() {
let error = Error::new("Test");
assert_eq!("Test", &error.description);
}
#[test]
fn test_from_cause() {
let cause = Error::new("Cause");
let error = Error::from_cause(cause);
assert_eq!("Cause", &error.description);
}
#[test]
fn test_display_fmt() {
let error = Error::new("Test");
let result = format!("{}", error);
assert_eq!("Test", result);
}
#[test]
fn test_from_other_error() {
use std::io;
let cause = io::Error::new(io::ErrorKind::Other, "Other error");
let error = Error::from(cause);
assert_eq!("Other error", &error.description);
}
}