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
100
101
102
103
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://wisagan.github.io/simple-error/simple_error/")]
#![deny(missing_docs)]
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SimpleError {
err: String,
}
impl SimpleError {
pub fn new<T: Into<String>>(t: T) -> SimpleError {
SimpleError{ err: t.into() }
}
pub fn from<T: std::error::Error>(t: T) -> SimpleError {
SimpleError{ err: format!("{}", t) }
}
}
impl fmt::Display for SimpleError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.err.fmt(f)
}
}
impl std::error::Error for SimpleError {
fn description(&self) -> &str {
&self.err
}
}
#[cfg(test)]
mod tests {
use super::SimpleError;
use std::error::Error;
use std::io;
#[test]
fn new_from_string() {
let err = SimpleError::new(String::from("an error from String"));
assert_eq!("an error from String", format!("{}", err));
assert_eq!("an error from String", err.description());
}
#[test]
fn new_from_str() {
let err = SimpleError::new("an error from str");
assert_eq!("an error from str", format!("{}", err));
}
#[test]
fn from_io_error() {
let err = SimpleError::from(io::Error::new(io::ErrorKind::Other, "oh no"));
assert_eq!("oh no", format!("{}", err));
}
}