error-collection 1.0.4

A generic collection around dynamic errors
Documentation
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
#![doc = include_str!("../README.md")]

use std::error::Error as StdError;
use std::fmt;

use derive_more::{Deref, DerefMut};

/// An explicit collection of Errors.
///
/// In order to be more concise, consider simply using [Errors].
pub type ErrorCollection = Errors;

/// A collection of multiple `anyhow::Error`s.
///
/// This is helpful because we often don't want to bail at the first error.
/// For example, take a simple method:
///
/// ```
/// # use anyhow::{bail, Result};
/// # #[derive(Debug, Clone, Copy)]
/// # struct Header { hash: u64 }
/// #
/// # fn read_header(raw: &[u8]) -> Result<Header> {
/// #     Ok(Header { hash: 0 })
/// # }
/// #
/// # fn hasher(contents: &str) -> u64 {
/// #     0
/// # }
/// #
/// fn check_file_integrity(raw: Vec<u8>) -> anyhow::Result<()> {
///   if raw.len() < 123 {
///      bail!("Data too short")
///   }
///
///   let Header { hash: expected_hash } = read_header(&raw[0..123])?;
///   let contents = str::from_utf8(&raw[123..])?;
///
///   if contents.len() < 2 {
///      bail!("Contents too short")
///   }
///
///   let data_hash = hasher(&contents);
///   if expected_hash != data_hash {
///      bail!("Header hash mismatch: {expected_hash} {data_hash}")
///   }
///
///   Ok(())
/// }
/// ```
///
/// We want the error to describe how the file is corrupted, but in our code we return
/// at the very first instance of an error. We are loosing valuable information during
/// runtime that could help debug a problem!
///
/// An [Errors] collection can help with this problem:
///
/// ```
/// # use anyhow::{anyhow, bail, Result};
/// # use error_collection::Errors;
/// # #[derive(Debug, Clone, Copy)]
/// # struct Header { hash: u64 }
/// #
/// # fn read_header(raw: &[u8]) -> Result<Header> {
/// #     Ok(Header { hash: 0 })
/// # }
/// #
/// # fn hasher(contents: &str) -> u64 {
/// #     0
/// # }
/// #
/// fn check_file_integrity(raw: Vec<u8>) -> anyhow::Result<()> {
///   if raw.len() < 123 {
///      bail!("Data too short")
///   }
///
///   let mut errors = Errors::new();
///
///   // Convert the results to options
///   let header = errors.collect(read_header(&raw[0..123]));
///   let contents = errors.collect(str::from_utf8(&raw[123..]));
///
///   if let Some(contents) = contents && contents.len() < 2 {
///     errors.append("Contents too short");
///   }
///
///   if let Some(data_hash) = contents.map(hasher) &&
///      let Some(Header { hash }) = header &&
///      hash != data_hash {
///      errors.push(anyhow!("Header hash mismatch: {hash} {data_hash}"));
///   }
///
///   errors.as_result() // Ok(()) if there are no errors
/// }
/// ```
///
/// ```text
/// 2 errors:
///    1. Missing lightbulb
///    2. Camera needs film
/// ```
#[derive(Default, Deref, DerefMut)]
pub struct Errors(pub Vec<anyhow::Error>);

impl Errors {
    /// Creates an empty error collection.
    pub fn new() -> Self {
        Self::default()
    }

    /// Pushes an error to the back of this collection.
    ///
    /// Note: Pushing an Errors will nest that collection in this one.
    /// See [Self::append] for an alternative that avoids nesting.
    pub fn push(&mut self, err: impl Into<anyhow::Error>) {
        self.0.push(err.into());
    }

    /// Appends another collection of [Errors] to the back of this one.
    ///
    /// Tip: You can append from `Options` and `Results` that implement `Into<anyhow::Error>`.
    pub fn append(&mut self, err: impl Into<Self>) {
        self.0.append(&mut err.into().0);
    }

    /// Unwraps the error contained in this Result. Errors get "collected" into the collection, and out comes the optional result.
    pub fn collect<T, E>(&mut self, result: Result<T, E>) -> Option<T>
    where
        E: Into<anyhow::Error>,
    {
        match result {
            Ok(value) => Some(value),
            Err(err) => {
                // Flatten out Errors
                self.append(err.into());
                None
            }
        }
    }

    /// Consumes the collection and returns the inner vector.
    pub fn into_vec(self) -> Vec<anyhow::Error> {
        self.0
    }

    /// Consumes the collection and returns a result.
    pub fn as_result(mut self) -> anyhow::Result<()> {
        match self.len() {
            0 => Ok(()),
            1 => Err(self.pop().unwrap()),
            _ => Err(self.into()),
        }
    }
}

const PADDING: usize = 3;

impl fmt::Debug for Errors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write!(f, "Errors ")?;
            let mut list = f.debug_list();
            for error in self.iter() {
                list.entry(error);
            }
            list.finish()
        } else {
            debug_collection(f, self, 0)
        }
    }
}

/// Custom debug formatter for Errors
fn debug_collection(f: &mut fmt::Formatter<'_>, errors: &Errors, indent: usize) -> fmt::Result {
    if errors.is_empty() {
        writeln!(f, "none")
    } else if errors.len() == 1 {
        debug_error(f, &errors[0], indent)
    } else {
        writeln!(f, "{} errors:", errors.len())?;
        for (idx, error) in errors.iter().enumerate() {
            write!(f, "{}{}. ", spaces(indent + PADDING), idx + 1)?;
            match error.downcast_ref::<Errors>() {
                None => debug_error(f, error, indent + PADDING)?,
                Some(errors) => debug_collection(f, errors, indent + PADDING)?,
            }
        }
        Ok(())
    }
}

/// Custom debug formatter for an anyhow::Error nested in a collection
fn debug_error(f: &mut fmt::Formatter<'_>, error: &anyhow::Error, indent: usize) -> fmt::Result {
    let padding = spaces(indent + PADDING);
    let error_string = format!("{error:?}");
    for (idx, line) in error_string.split('\n').enumerate() {
        let padding = if idx == 0 { "" } else { padding };
        writeln!(f, "{padding}{line}")?;
    }
    Ok(())
}

impl fmt::Display for Errors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Errors: ")?;

        if self.is_empty() {
            return writeln!(f, "none");
        }

        let mut first = true;
        display_collection(f, self, &mut first)?;
        writeln!(f)
    }
}

/// Custom display formatter for Errors
fn display_collection(
    f: &mut fmt::Formatter<'_>,
    errors: &Errors,
    first: &mut bool,
) -> fmt::Result {
    for error in errors.iter() {
        match error.downcast_ref::<Errors>() {
            Some(errors) => display_collection(f, errors, first)?,
            None => display_error(f, error, first)?,
        }
    }
    Ok(())
}

/// Custom display formatter for an anyhow::Error nested in a collection
fn display_error(
    f: &mut fmt::Formatter<'_>,
    error: &anyhow::Error,
    first: &mut bool,
) -> fmt::Result {
    if *first {
        *first = false;
    } else {
        write!(f, ", ")?;
    }

    if f.alternate() {
        write!(f, "{error:#}")
    } else {
        write!(f, "{error}")
    }
}

/// Zero-alloc version of " ".repeat(x)
fn spaces(indent: usize) -> &'static str {
    &"                                "[..indent.min(32)]
}

impl StdError for Errors {}

impl From<&str> for Errors {
    fn from(value: &str) -> Self {
        Self(vec![anyhow::anyhow!("{value}")])
    }
}

impl From<String> for Errors {
    fn from(value: String) -> Self {
        Self(vec![anyhow::anyhow!(value)])
    }
}

impl<T> From<Option<T>> for Errors
where
    T: Into<anyhow::Error>,
{
    fn from(result: Option<T>) -> Self {
        match result {
            Some(err) => err.into().into(),
            None => Self::default(),
        }
    }
}

impl<T, E> From<Result<T, E>> for Errors
where
    E: Into<anyhow::Error>,
{
    fn from(result: Result<T, E>) -> Self {
        match result {
            Ok(_) => Self::default(),
            Err(err) => err.into().into(),
        }
    }
}

impl From<Vec<anyhow::Error>> for Errors {
    fn from(errors: Vec<anyhow::Error>) -> Self {
        Self(errors)
    }
}

impl From<anyhow::Error> for Errors {
    fn from(error: anyhow::Error) -> Self {
        match error.downcast::<Self>() {
            Ok(errors) => errors,
            Err(error) => Self(vec![error]),
        }
    }
}

impl<T> From<Errors> for anyhow::Result<T>
where
    T: Default,
{
    fn from(mut value: Errors) -> Self {
        match value.len() {
            0 => Ok(T::default()),
            1 => Err(value.pop().unwrap()),
            _ => Err(value.into()),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io;

    use anyhow::{Context, anyhow};

    use super::*;

    #[test]
    fn push() {
        let mut nested = Errors::new();
        nested.push(anyhow!("Generic error 1"));
        nested.push(anyhow!("Generic error 2"));
        nested.push(anyhow!("Generic error 3"));

        let mut errors = Errors::new();
        errors.push(nested);
        errors.push(anyhow!("Generic error 4"));
        errors.push(io::Error::from_raw_os_error(22));

        assert_eq!(errors.len(), 3);
    }

    #[test]
    fn append() {
        let mut nested = Errors::new();
        nested.append(vec![anyhow!("Generic error 1"), anyhow!("Generic error 2")]);

        let mut errors = Errors::new();
        errors.append(nested);
        errors.append(anyhow!("Generic error 3"));

        assert_eq!(errors.len(), 3);
    }

    #[test]
    fn collect() {
        let mut errors = Errors::new();

        let result: Result<(), anyhow::Error> = Ok(());
        assert_eq!(errors.collect(result), Some(()));

        let result: Result<(), anyhow::Error> = Err(anyhow!("Generic error 1"));
        assert_eq!(errors.collect(result), None);

        assert_eq!(errors.len(), 1);
    }

    #[test]
    fn collect_nested() {
        let mut nested = Errors::new();
        nested.push(anyhow!("Generic error 1"));
        nested.push(anyhow!("Generic error 2"));
        nested.push(anyhow!("Generic error 3"));

        let mut errors = Errors::new();

        let result: Result<(), Errors> = Err(nested);
        assert_eq!(errors.collect(result), None);

        assert_eq!(errors.len(), 3);
    }

    fn deeply_nested() -> Errors {
        let mut child = Errors::new();
        child.push(anyhow!("Generic error 2"));
        child.push(anyhow!("Generic error 3\nnew line"));
        child.push(Errors(vec![anyhow!("Generic error 4")]));

        let mut parent = Errors::new();
        parent.push(child);
        parent.push(io::Error::from_raw_os_error(1));

        let mut errors = Errors::new();
        errors.push(
            anyhow::Result::<()>::Err(anyhow!("Original error"))
                .context("Generic error 1")
                .unwrap_err(),
        );
        errors.push(parent);
        errors
    }

    #[test]
    fn display() {
        let errors = deeply_nested();
        assert_eq!(
            format!("{errors}"),
            "Errors: Generic error 1, Generic error 2, Generic error 3\n\
            new line, Generic error 4, Operation not permitted (os error 1)\n"
        );
    }

    #[test]
    fn display_alternate() {
        let errors = deeply_nested();
        assert_eq!(
            format!("{errors:#}"),
            "Errors: Generic error 1: Original error, Generic error 2, Generic error 3\n\
            new line, Generic error 4, Operation not permitted (os error 1)\n"
        );
    }

    #[test]
    fn debug() {
        let errors = deeply_nested();
        assert_eq!(
            format!("{errors:?}"),
            "2 errors:
                1. Generic error 1
                   \n      \
                   Caused by:
                       Original error
                2. 2 errors:
                   1. 3 errors:
                      1. Generic error 2
                      2. Generic error 3
                         new line
                      3. Generic error 4
                   2. Operation not permitted (os error 1)\n"
                .replace("\n             ", "\n")
        );
    }

    #[test]
    fn debug_alternate() {
        let errors = deeply_nested();
        println!("{errors:#?}");
        assert_eq!(
            format!("{errors:#?}"),
            "Errors [
                Error {
                    context: \"Generic error 1\",
                    source: \"Original error\",
                },
                Errors [
                    Errors [
                        \"Generic error 2\",
                        \"Generic error 3\\nnew line\",
                        Errors [
                            \"Generic error 4\",
                        ],
                    ],
                    Os {
                        code: 1,
                        kind: PermissionDenied,
                        message: \"Operation not permitted\",
                    },
                ],
            ]"
            .replace("\n            ", "\n")
        );
    }
}