error-trees 0.2.0

Fail with multiple errors, istead of only the first.
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
//! This crate provides a convenient way of handling multiple
//! errors.
//!
//! Instead of returning early with the first error in your app,
//! it helps you store the errors that occur in a tree structure.
//! It lets you label the errors, and flatten then into a list
//! to present to the user.
use itertools::Itertools;

/// The error Tree structure.
///
/// - `L` is the Label type.
/// - `E` is the inner Error type. It can be an error enum (from the thiserror package).
#[derive(Debug)]
pub enum ErrorTree<L, E> {
    /// Stores your single error type.
    Leaf(E),
    /// Adds a label to the subtree.
    Edge(L, Box<ErrorTree<L, E>>),
    /// Groups multiple subtrees at the same level.
    Vec(Vec<ErrorTree<L, E>>),
}

impl<L, E> ErrorTree<L, E> {
    /**
    Creates a `Leaf` tree from an `error`.

    ```rust
    # use itertools::*;
    # use error_trees::*;
    struct Error(String);
    let error_tree = ErrorTree::<&'static str, _>::leaf(Error("error".into()));
    ```
    */
    pub fn leaf(error: E) -> Self {
        Self::Leaf(error)
    }
}

/// The flattened error type
#[derive(Debug)]
pub struct FlatError<L, E> {
    /// The path from the leaf to the root of the tree.
    pub path: Vec<L>,
    /// The error
    pub error: E,
}

impl<L, E> ErrorTree<L, E>
where
    L: Clone,
{
    /**
    Flattens the error tree in a `Vec` of `FlatError`s.

    ```rust
    # use itertools::*;
    # use error_trees::*;
    #[derive(Debug)]
    struct Error(String);

    let error_1 = ErrorTree::leaf(Error("error1".into())).with_label("label1");
    let error_2 = ErrorTree::leaf(Error("error2".into())).with_label("label2");

    let errors = vec![error_1, error_2];

    let tree: ErrorTree<&'static str, Error> = errors.into();
    let tree = tree.with_label("parent_label");

    let flat_errors = tree.flatten_tree();

    assert!(
        matches!(
            &flat_errors[..],
            [
                FlatError {
                    path: path1,
                    error: Error(error1),
                },
                FlatError {
                    path: path2,
                    error: Error(error2),
                },
            ]
            if path1 == &vec!["label1", "parent_label"]
            && path2 == &vec!["label2", "parent_label"]
            && error1 == "error1"
            && error2 == "error2"
        ),
        "unexpected: {:#?}",
        flat_errors
    );
    ```
    */
    pub fn flatten_tree(self) -> Vec<FlatError<L, E>> {
        match self {
            ErrorTree::Leaf(error) => vec![FlatError {
                path: Vec::new(),
                error,
            }],
            ErrorTree::Edge(label, tree) => {
                let mut flat_errors = tree.flatten_tree();
                for flat in &mut flat_errors {
                    flat.path.push(label.clone());
                }
                flat_errors
            }
            ErrorTree::Vec(errors) => errors
                .into_iter()
                .flat_map(|tree| tree.flatten_tree())
                .collect_vec(),
        }
    }
}

/// Adds a label to the error tree.
pub trait IntoErrorTree<L, E> {
    /**
    Adds a `label` to an error tree.
    ```rust
    # use error_trees::*;
    struct Error(String);
    let leaf = ErrorTree::leaf(Error("a regular error".into()));
    let labeled_leaf = leaf.with_label("the label");
    ```
    */
    fn with_label(self, label: L) -> ErrorTree<L, E>;
}

impl<L, E> IntoErrorTree<L, E> for E
where
    E: Into<ErrorTree<L, E>>,
{
    fn with_label(self, label: L) -> ErrorTree<L, E> {
        ErrorTree::Edge(label, Box::new(self.into()))
    }
}

impl<L, E> IntoErrorTree<L, E> for ErrorTree<L, E> {
    fn with_label(self, label: L) -> ErrorTree<L, E> {
        ErrorTree::Edge(label, Box::new(self))
    }
}

impl<L, E> From<Vec<ErrorTree<L, E>>> for ErrorTree<L, E> {
    fn from(subtrees: Vec<ErrorTree<L, E>>) -> Self {
        ErrorTree::Vec(subtrees)
    }
}

impl<L, E> From<Vec<E>> for ErrorTree<L, E>
where
    E: IntoErrorTree<L, E>,
    ErrorTree<L, E>: From<E>,
{
    fn from(errors: Vec<E>) -> Self {
        ErrorTree::Vec(errors.into_iter().map(|x| x.into()).collect_vec())
    }
}

/// Convenience trait to convert tuple of `(success: T, errors: Vec<E>)` to a `result : Result<T, ErrorTree<L, E>>`
pub trait IntoResult<T, E> {
    /**
    Turns `self` into a `Result`.

    For tuples of `(success: T, errors: Vec<E>)`:
    - It checks if `errors` is empty.
        - If true, it will return `Ok(success)`.
        - Otherwise it will return `Err(errors)`.

    ```rust
    # use itertools::*;
    # use error_trees::*;
    struct Error(String);
    impl<L> From<Error> for ErrorTree<L, Error> {
        fn from(e: Error) -> Self {
            Self::leaf(e)
        }
    }

    let result1: Result<(), _> = Err(Error("first".into())).label_error("one");
    let result2: Result<(), _> = Err(Error("second".into())).label_error("two");

    let final_result: Result<Vec<_>, ErrorTree<_, _>> = vec![result1, result2]
        .into_iter()
        .partition_result()
        .into_result();
    ```

    For `errors: Vec<E>`:
    - It checks if `errors` is empty.
    - If true, it will return `Ok(())`.
    - Otherwise, it will return `Err(errors)`.

    Since the trait is implemented for tuples of `(success: T, errors: Vec<E>)`
    and for `Vec<E>`, it works well with `partition_result` from the `itertools` crate!

    ```rust
    # use itertools::*;
    # use error_trees::*;
    struct Error(String);

    let error1 = ErrorTree::leaf(Error("first".into())).with_label("one");
    let error2 = ErrorTree::leaf(Error("second".into())).with_label("two");

    let final_result: Result<_, ErrorTree<_, _>> = vec![error1, error2]
        .into_result();
    ```
    */
    fn into_result(self) -> Result<T, E>;
}

impl<T, IE, E> IntoResult<T, E> for (T, Vec<IE>)
where
    Vec<IE>: Into<E>,
{
    fn into_result(self) -> Result<T, E> {
        let (oks, errs) = self;
        if errs.is_empty() {
            Ok(oks)
        } else {
            Err(errs.into())
        }
    }
}

impl<IE, E> IntoResult<(), E> for Vec<IE>
where
    Vec<IE>: Into<E>,
{
    fn into_result(self) -> Result<(), E> {
        if self.is_empty() {
            Ok(())
        } else {
            Err(self.into())
        }
    }
}

/// Convenience trait to label errors within a `Result`.
pub trait LabelResult<T, L, E> {
    /**
    Maps a label to the `ErrorTree` within the result.

    ```rust
    # use itertools::*;
    # use error_trees::*;
    struct Error(String);
    let result: Result<(), ErrorTree<&'static str, Error>> = Ok(());
    let labeled_result = result.label_error("the label");
    ```
    */
    fn label_error(self, label: L) -> Result<T, ErrorTree<L, E>>;
}

impl<T, L, E> LabelResult<T, L, E> for Result<T, E>
where
    ErrorTree<L, E>: From<E>,
{
    fn label_error(self, label: L) -> Result<T, ErrorTree<L, E>> {
        self.map_err(|e| {
            let tree: ErrorTree<L, E> = e.into();
            tree.with_label(label)
        })
    }
}

impl<T, L, E> LabelResult<T, L, E> for Result<T, ErrorTree<L, E>> {
    fn label_error(self, label: L) -> Result<T, ErrorTree<L, E>> {
        self.map_err(|tree| tree.with_label(label))
    }
}

pub trait FlattenResultErrors<T, L, E> {
    fn flatten_results(self) -> Result<T, Vec<FlatError<L, E>>>;
}

impl<T, L, E> FlattenResultErrors<T, L, E> for Result<T, ErrorTree<L, E>>
where
    L: Clone,
{
    fn flatten_results(self) -> Result<T, Vec<FlatError<L, E>>> {
        self.map_err(|tree| tree.flatten_tree())
    }
}

#[cfg(test)]
mod tests {
    use itertools::Itertools;

    use super::*;

    fn faulty(error: &str) -> Result<(), Error> {
        Err(Error(error.into()))
    }

    #[test]
    fn can_build_tree_from_vec_of_results() {
        let result_1 = faulty("error1").map_err(|e| e.with_label("label1"));
        let result_2 = faulty("error2").map_err(|e| e.with_label("label2"));

        let (_, errors): (Vec<_>, Vec<_>) = vec![result_1, result_2].into_iter().partition_result();

        let tree: ErrorTree<&'static str, Error> = errors.into();
        let tree = tree.with_label("parent_label");

        let flat_errors = tree.flatten_tree();

        assert!(
            matches!(
                &flat_errors[..],
                [
                    FlatError {
                        path: path1,
                        error: Error(error1),
                    },
                    FlatError {
                        path: path2,
                        error: Error(error2),
                    },
                ]
                if path1 == &vec!["label1", "parent_label"]
                && path2 == &vec!["label2", "parent_label"]
                && error1 == "error1"
                && error2 == "error2"
            ),
            "unexpected: {:#?}",
            flat_errors
        );
    }

    #[test]
    fn can_call_into_result_from_vec_of_results() {
        let result_1 = faulty("error1").map_err(|e| e.with_label("label1"));
        let result_2 = faulty("error2").map_err(|e| e.with_label("label2"));

        let result: Result<Vec<()>, ErrorTree<_, _>> = vec![result_1, result_2]
            .into_iter()
            .partition_result()
            .into_result();

        let flat_result = result.map_err(|e| e.flatten_tree());

        let flat_errors = flat_result.unwrap_err();

        assert!(
            matches!(
                &flat_errors[..],
                [
                    FlatError {
                        path: path1,
                        error: Error(error1),
                    },
                    FlatError {
                        path: path2,
                        error: Error(error2),
                    },
                ]
                if path1 == &vec!["label1"]
                && path2 == &vec!["label2"]
                && error1 == "error1"
                && error2 == "error2"
            ),
            "unexpected: {:#?}",
            flat_errors
        );
    }

    #[test]
    fn can_call_into_result_from_vec_of_errors() {
        let error1 = Error("error1".into()).with_label("label1");
        let error2 = Error("error2".into()).with_label("label2");

        let result: Result<_, ErrorTree<_, _>> = vec![error1, error2].into_result();

        let flat_result = result.map_err(|e| e.flatten_tree());

        let flat_errors = flat_result.unwrap_err();

        assert!(
            matches!(
                &flat_errors[..],
                [
                    FlatError {
                        path: path1,
                        error: Error(error1),
                    },
                    FlatError {
                        path: path2,
                        error: Error(error2),
                    },
                ]
                if path1 == &vec!["label1"]
                && path2 == &vec!["label2"]
                && error1 == "error1"
                && error2 == "error2"
            ),
            "unexpected: {:#?}",
            flat_errors
        );
    }

    // For the README

    // The error type
    #[derive(Debug)]
    struct Error(String);

    impl<L> From<Error> for ErrorTree<L, Error> {
        fn from(e: Error) -> Self {
            Self::leaf(e)
        }
    }

    // A function that returns an error
    fn faulty_function() -> Result<(), Error> {
        Err(Error("error".into()))
    }

    // A function that returns more than one error
    fn parent_function() -> Result<Vec<()>, ErrorTree<&'static str, Error>> {
        let result1 = faulty_function().label_error("first faulty");
        let result2 = faulty_function().label_error("second faulty");

        let result: Result<_, ErrorTree<_, _>> = vec![result1, result2]
            .into_iter()
            .partition_result::<Vec<_>, Vec<_>, _, _>()
            .into_result();
        result.label_error("parent function")
    }

    // your main function
    #[test]
    fn main_function() {
        let result = parent_function();

        let flat_results = result.flatten_results();
        let flat_errors: Vec<FlatError<&str, Error>> = flat_results.unwrap_err();

        assert!(
            matches!(
                &flat_errors[..],
                [
                    FlatError {
                        path: path1,
                        error: Error(_),
                    },
                    FlatError {
                        path: path2,
                        error: Error(_),
                    },
                ]
                if path1 == &vec!["first faulty", "parent function"]
                && path2 == &vec!["second faulty", "parent function"]
            ),
            "unexpected: {:#?}",
            flat_errors
        );
    }
}