1use std::fmt;
11
12pub mod codes {
15 pub const OK: i32 = 0;
17 pub const FAILURE: i32 = 1;
19 pub const USAGE: i32 = 2;
21 pub const NOT_FOUND: i32 = 3;
23 pub const PERMISSION: i32 = 4;
25 pub const CANCELLED: i32 = 5;
27}
28
29#[derive(Debug, Clone)]
32pub struct Error {
33 pub message: String,
34 pub code: i32,
35 pub notes: Vec<String>,
37}
38
39impl Error {
40 pub fn msg<S: Into<String>>(message: S) -> Self {
42 Error {
43 message: message.into(),
44 code: codes::FAILURE,
45 notes: Vec::new(),
46 }
47 }
48
49 pub fn usage<S: Into<String>>(message: S) -> Self {
51 Error {
52 message: message.into(),
53 code: codes::USAGE,
54 notes: Vec::new(),
55 }
56 }
57
58 pub fn not_found<S: Into<String>>(message: S) -> Self {
60 Error {
61 message: message.into(),
62 code: codes::NOT_FOUND,
63 notes: Vec::new(),
64 }
65 }
66
67 pub fn permission<S: Into<String>>(message: S) -> Self {
69 Error {
70 message: message.into(),
71 code: codes::PERMISSION,
72 notes: Vec::new(),
73 }
74 }
75
76 pub fn cancelled<S: Into<String>>(message: S) -> Self {
78 Error {
79 message: message.into(),
80 code: codes::CANCELLED,
81 notes: Vec::new(),
82 }
83 }
84
85 pub fn with_code(mut self, code: i32) -> Self {
87 self.code = code;
88 self
89 }
90
91 pub fn note<S: Into<String>>(mut self, note: S) -> Self {
93 self.notes.push(note.into());
94 self
95 }
96}
97
98impl fmt::Display for Error {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 write!(f, "{}", self.message)
101 }
102}
103
104impl std::error::Error for Error {}
105
106macro_rules! from_std {
112 ($($ty:path),* $(,)?) => {
113 $(
114 impl From<$ty> for Error {
115 fn from(e: $ty) -> Self {
116 Error::msg(e.to_string())
117 }
118 }
119 )*
120 };
121}
122
123from_std!(
124 std::io::Error,
125 std::num::ParseIntError,
126 std::num::ParseFloatError,
127 std::str::Utf8Error,
128 std::string::FromUtf8Error,
129 std::num::TryFromIntError,
130);
131
132impl Error {
133 pub fn wrap<E: std::fmt::Display>(e: E) -> Self {
136 Error::msg(e.to_string())
137 }
138}
139
140pub type Result<T> = std::result::Result<T, Error>;
142
143#[derive(Debug, Default, Clone)]
146pub struct ErrorSet {
147 errors: Vec<Error>,
148}
149
150impl ErrorSet {
151 pub fn new() -> Self {
152 ErrorSet { errors: Vec::new() }
153 }
154
155 pub fn push(&mut self, e: Error) {
157 self.errors.push(e);
158 }
159
160 pub fn absorb<T>(&mut self, r: Result<T>) -> Option<T> {
163 match r {
164 Ok(v) => Some(v),
165 Err(e) => {
166 self.errors.push(e);
167 None
168 }
169 }
170 }
171
172 pub fn is_empty(&self) -> bool {
173 self.errors.is_empty()
174 }
175
176 pub fn len(&self) -> usize {
177 self.errors.len()
178 }
179
180 pub fn errors(&self) -> &[Error] {
181 &self.errors
182 }
183
184 pub fn into_result(self) -> Result<()> {
188 if self.errors.is_empty() {
189 return Ok(());
190 }
191 let code = self.errors.iter().map(|e| e.code).max().unwrap_or(codes::FAILURE);
192 let mut summary = Error::msg(format!("{} operation(s) failed", self.errors.len()))
193 .with_code(code);
194 for e in &self.errors {
195 summary.notes.push(e.message.clone());
196 for n in &e.notes {
197 summary.notes.push(format!(" {}", n));
198 }
199 }
200 Err(summary)
201 }
202}
203
204#[cfg(test)]
205mod tests {
206 use super::*;
207
208 #[test]
209 fn constructors_set_codes() {
210 assert_eq!(Error::msg("x").code, codes::FAILURE);
211 assert_eq!(Error::usage("x").code, codes::USAGE);
212 assert_eq!(Error::not_found("x").code, codes::NOT_FOUND);
213 assert_eq!(Error::permission("x").code, codes::PERMISSION);
214 assert_eq!(Error::cancelled("x").code, codes::CANCELLED);
215 }
216
217 #[test]
218 fn error_set_collects_and_reports() {
219 let mut s = ErrorSet::new();
220 assert!(s.is_empty());
221 s.push(Error::usage("first"));
222 s.push(Error::not_found("second"));
223 assert_eq!(s.len(), 2);
224 let e = s.into_result().unwrap_err();
225 assert_eq!(e.code, codes::NOT_FOUND);
227 assert_eq!(e.notes.len(), 2);
228 }
229
230 #[test]
231 fn empty_error_set_is_ok() {
232 assert!(ErrorSet::new().into_result().is_ok());
233 }
234
235 #[test]
236 fn absorb_returns_ok_value() {
237 let mut s = ErrorSet::new();
238 let v = s.absorb(Ok::<i32, Error>(5));
239 assert_eq!(v, Some(5));
240 let n = s.absorb(Err::<i32, Error>(Error::msg("bad")));
241 assert_eq!(n, None);
242 assert_eq!(s.len(), 1);
243 }
244
245 #[test]
246 fn io_error_converts() {
247 let io = std::io::Error::new(std::io::ErrorKind::NotFound, "nope");
248 let e: Error = io.into();
249 assert_eq!(e.code, codes::FAILURE);
250 }
251}