error_set 0.9.1

Quick error declarations and automatic conversions between errors for precisely typed error handling. Inspired by Zig's error set type.
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
# Error Set

[<img alt="github" src="https://img.shields.io/badge/github-mcmah309/error_set-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/mcmah309/error_set)
[<img alt="crates.io" src="https://img.shields.io/crates/v/error_set.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/error_set)
[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-error_set-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs" height="20">](https://docs.rs/error_set)
[<img alt="test status" src="https://img.shields.io/github/actions/workflow/status/mcmah309/error_set/ci.yml?branch=master&style=for-the-badge" height="20">](https://github.com/mcmah309/error_set/actions?query=branch%3Amaster)

Error Set simplifies error management by providing a streamlined method for defining errors and easily converting between them.

Error Set is inspired by Zig's [error set](https://ziglang.org/documentation/master/#Error-Set-Type), and offers similar functionality.

Instead of defining various enums/structs for errors and hand rolling relations, use an error set:
```rust
use error_set::error_set;

error_set! {
    /// The syntax below aggregates the referenced error variants.
    /// Notice `:=`. This symbol comes from mathematics and means "is defined as".
    MediaError := DownloadError || BookParsingError

    /// Since all variants in [DownloadError] are in [MediaError], a
    /// [DownloadError] can be turned into a [MediaError] with just `.into()` or `?`. 
    DownloadError := {
        #[display("Easily add custom display messages")]
        InvalidUrl,
        /// The `From` trait for `std::io::Error` will also be automatically derived
        #[display("Display messages work just like the `format!` macro {0}")]
        IoError(std::io::Error),
    }

    /// Traits like `Debug`, `Display`, `Error`, and `From` are all automatically derived
    #[derive(Clone)]
    BookParsingError := { MissingBookDescription, } || BookSectionParsingError

    BookSectionParsingError := {
        /// Inline structs are also supported
        #[display("Display messages can also reference fields, like {field}")]
        MissingField {
            field: String
        },
        NoContent,
    }
}
```
<details>

  <summary>Cargo Expand</summary>

```rust
#[doc = " The syntax below aggregates the referenced error variants."]
#[doc = " Notice `:=`. This symbol comes from mathematics and means \"is defined as\"."]
#[derive(Debug)]
pub enum MediaError {
    InvalidUrl, #[doc = " The `From` trait for `std::io::Error` will also be automatically derived"]
    IoError(std::io::Error),MissingBookDescription, #[doc = " Inline structs are also supported"]
    MissingField {
        field:String
    },NoContent,
}
#[allow(unused_qualifications)]
impl core::error::Error for MediaError {
    fn source(&self) -> Option< &(dyn core::error::Error+'static)>{
        match self {
            MediaError::IoError(source) => source.source(), 
            #[allow(unreachable_patterns)]
            _ => None,
        
            }
    }
}
impl core::fmt::Display for MediaError {
    #[inline]
    fn fmt(&self,f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match& *self {
            MediaError::InvalidUrl => write!(f,"{}","Easily add custom display messages"),
            MediaError::IoError(source) => write!(f,"Display messages work just like the `format!` macro {0}",source),
            MediaError::MissingBookDescription => write!(f,"{}",concat!(stringify!(MediaError),"::",stringify!(MissingBookDescription))),
            MediaError::MissingField {
                field
            } => write!(f,"Display messages can also reference fields, like {field}"),
            MediaError::NoContent => write!(f,"{}",concat!(stringify!(MediaError),"::",stringify!(NoContent))),
        
            }
    }
}
impl From<DownloadError>for MediaError {
    fn from(error:DownloadError) -> Self {
        match error {
            DownloadError::InvalidUrl => MediaError::InvalidUrl,
            DownloadError::IoError(source) => MediaError::IoError(source),
        
            }
    }
}
impl From<BookParsingError>for MediaError {
    fn from(error:BookParsingError) -> Self {
        match error {
            BookParsingError::MissingBookDescription => MediaError::MissingBookDescription,
            BookParsingError::MissingField {
                field
            } => MediaError::MissingField {
                field
            },
            BookParsingError::NoContent => MediaError::NoContent,
        
            }
    }
}
impl From<BookSectionParsingError>for MediaError {
    fn from(error:BookSectionParsingError) -> Self {
        match error {
            BookSectionParsingError::MissingField {
                field
            } => MediaError::MissingField {
                field
            },
            BookSectionParsingError::NoContent => MediaError::NoContent,
        
            }
    }
}
impl From<std::io::Error>for MediaError {
    fn from(error:std::io::Error) -> Self {
        MediaError::IoError(error)
    }
}
#[doc = " Since all variants in [DownloadError] are in [MediaError], a"]
#[doc = " [DownloadError] can be turned into a [MediaError] with just `.into()` or `?`."]
#[derive(Debug)]
pub enum DownloadError {
    InvalidUrl, #[doc = " The `From` trait for `std::io::Error` will also be automatically derived"]
    IoError(std::io::Error),
}
#[allow(unused_qualifications)]
impl core::error::Error for DownloadError {
    fn source(&self) -> Option< &(dyn core::error::Error+'static)>{
        match self {
            DownloadError::IoError(source) => source.source(), 
            #[allow(unreachable_patterns)]
            _ => None,
        
            }
    }
}
impl core::fmt::Display for DownloadError {
    #[inline]
    fn fmt(&self,f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match& *self {
            DownloadError::InvalidUrl => write!(f,"{}","Easily add custom display messages"),
            DownloadError::IoError(source) => write!(f,"Display messages work just like the `format!` macro {0}",source),
        
            }
    }
}
impl From<std::io::Error>for DownloadError {
    fn from(error:std::io::Error) -> Self {
        DownloadError::IoError(error)
    }
}
#[doc = " Traits like `Debug`, `Display`, `Error`, and `From` are all automatically derived"]
#[derive(Clone)]
#[derive(Debug)]
pub enum BookParsingError {
    MissingBookDescription, #[doc = " Inline structs are also supported"]
    MissingField {
        field:String
    },NoContent,
}
#[allow(unused_qualifications)]
impl core::error::Error for BookParsingError{}

impl core::fmt::Display for BookParsingError {
    #[inline]
    fn fmt(&self,f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match& *self {
            BookParsingError::MissingBookDescription => write!(f,"{}",concat!(stringify!(BookParsingError),"::",stringify!(MissingBookDescription))),
            BookParsingError::MissingField {
                field
            } => write!(f,"Display messages can also reference fields, like {field}"),
            BookParsingError::NoContent => write!(f,"{}",concat!(stringify!(BookParsingError),"::",stringify!(NoContent))),
        
            }
    }
}
impl From<BookSectionParsingError>for BookParsingError {
    fn from(error:BookSectionParsingError) -> Self {
        match error {
            BookSectionParsingError::MissingField {
                field
            } => BookParsingError::MissingField {
                field
            },
            BookSectionParsingError::NoContent => BookParsingError::NoContent,
        
            }
    }
}
#[derive(Debug)]
pub enum BookSectionParsingError {
    #[doc = " Inline structs are also supported"]
    MissingField {
        field:String
    },NoContent,
}
#[allow(unused_qualifications)]
impl core::error::Error for BookSectionParsingError{}

impl core::fmt::Display for BookSectionParsingError {
    #[inline]
    fn fmt(&self,f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match& *self {
            BookSectionParsingError::MissingField {
                field
            } => write!(f,"Display messages can also reference fields, like {field}"),
            BookSectionParsingError::NoContent => write!(f,"{}",concat!(stringify!(BookSectionParsingError),"::",stringify!(NoContent))),
        
            }
    }
}
```
</details>

The above error set can also be written as the full expansion (without the `||` operator).

<details>

  <summary>Full Expansion Representation</summary>

\*Comments and messages removed for brevity\*

```rust
error_set::error_set! {
    MediaError := {
        InvalidUrl,
        IoError(std::io::Error),
        MissingBookDescription,
        MissingField {
            field: String
        },
        NoContent,
    }
    DownloadError := {
        InvalidUrl,
        IoError(std::io::Error),
    }
    BookParsingError := {
        MissingBookDescription,
        MissingField {
            field: String
        },
        NoContent,
    }
    BookSectionParsingError := {
        MissingField {
            field: String
        },
        NoContent,
    }
}
```
</details>

Any above subset can be converted into a superset with `.into()` or `?`. 
This makes correctly scoping and passing up call chains a breeze.

<details>

  <summary>Basic Example</summary>

```rust
use error_set::{error_set, CoerceResult};

error_set! {
    MediaError := DownloadError || BookParsingError
    DownloadError := {
        InvalidUrl,
        IoError(std::io::Error),
    }
    BookParsingError := { MissingBookDescription, } || BookSectionParsingError
    BookSectionParsingError := {
        MissingField {
            field: String
        },
        NoContent,
    }
}

fn main() {
    let book_section_parsing_error: BookSectionParsingError =
        BookSectionParsingError::MissingField {
            field: "author".to_string(),
        };
    let book_parsing_error: BookParsingError = book_section_parsing_error.into();
    assert!(matches!(
        book_parsing_error,
        BookParsingError::MissingField { field: _ }
    ));
    let media_error: MediaError = book_parsing_error.into();
    assert!(matches!(media_error, MediaError::MissingField { field: _ }));

    let io_error = std::io::Error::new(std::io::ErrorKind::OutOfMemory, "oops out of memory");
    let result_download_error: Result<(), DownloadError> = Err(io_error).coerce(); // == .map_err(Into::into);
    let result_media_error: Result<(), MediaError> = result_download_error.map_err(Into::into);
    assert!(matches!(result_media_error, Err(MediaError::IoError(_))));
}
```
</details>


The typical project approach is to have one `errors.rs` file with a single `error_set`. This keeps
all the errors in one place and allows your IDE to autocomplete `crate::errors::` with of all errors.
But `error_set!` can also be used for quick errors "unions", no longer requiring users to 
handwrite `From<..>` or use `.map_err(..)` for these simple cases.
e.g.
```rust
use std::collections::HashMap;
use jsonwebtoken::DecodingKey;

error_set::error_set! {
    JwtVerifierCreationError := {
        Reqwest(reqwest::Error),
        Jwt(jsonwebtoken::errors::Error),
    }
}

impl JwtVerifier {
    pub async fn new(project_id: String) -> Result<Self, JwtVerifierCreationError> {
        let public_keys = Self::fetch_public_keys().await?; // Err is `reqwest::Error`
        let decoding_keys: HashMap<String, DecodingKey> = public_keys
            .into_iter()
            .map(|(key, value)| {
                DecodingKey::from_rsa_pem(value.as_bytes())
                    .map(|decoding_key| (key, decoding_key))
            })
            .collect::<Result<_,_>>()?; // Err is `jsonwebtoken::errors::Error`
        unimplemented!()
    }

    async fn fetch_public_keys() -> Result<HashMap<String, String>, reqwest::Error> {
        unimplemented!()
    }
}

struct JwtVerifier;
```

## More Details

### Source Variants

Error sets that have source variants (aka wrapped variants), will delegate the `Error` trait's `source()` method to the
correct source branch's wrapped error. `From` traits are also automatically generated from the
inner type to the Error enum.

#### Source Tuple Variants
Source tuple variants are the most common source variant. Declared like
```rust
error_set::error_set! {
    ErrorEnum := {
        IoError(std::io::Error),
        FmtError(std::fmt::Error),
    }
}
```
Which has the generated enum
```rust
pub enum ErrorEnum {
    IoError(std::io::Error),
    FmtError(std::fmt::Error),
}
```

#### Source Struct Variants
Source struct variants are also supported, declared like so
```rust
error_set::error_set! {
    ErrorEnum := {
        IoError(std::io::Error) {} // Note the `{}`
    }
}
```
Which has the generated enum
```rust
pub enum ErrorEnum {
    IoError {
        source: std::io::Error,
    }
}
```
Source structs become useful when you want to attach additional fields to an error
```rust
error_set::error_set! {
    ErrorEnum := {
        IoError(std::io::Error) {
            field1: String,
            field2: &'static str,
        }
    }
}
```
Which has the generated enum
```rust
pub enum ErrorEnum {
    IoError {
        source: std::io::Error,
        field1: String,
        field2: &'static str,
    }
}
```
A `From` implementation for the inner `source` is not automatically generated for source struct variants that have fields,
like above.

#### Multiple Source Variants Of The Same Type
Error sets can have multiple source variants of the same type. e.g.
```rust
error_set::error_set! {
    ErrorEnum3 := {
        IoError1(std::io::Error),
        IoError2(std::io::Error),
    }
}
```
But a `From` implementation will not be automatically generated for these cases.

### Aggregations And Conversions

Error set uses `||` (or) for aggregation, which performs an "or" operation on the set space. 
Note, `||` is not needed, just a convenience -
```rust
error_set::error_set! {
    ErrorEnum1 := {
        Variant1,
        Variant2
    } || ErrorEnum2
    ErrorEnum2 := {
        Variant3
    }
}
```
is equivalent to
```rust
error_set::error_set! {
    ErrorEnum1 := {
        Variant1,
        Variant2,
        Variant3,
    }
    ErrorEnum2 := {
        Variant3
    }
}
```

For one type to be converted into another it needs to be considered a subset of the target type.
Thus in the example above, `ErrorEnum2` can be converted into `ErrorEnum1` with `.into()` or `?`.

### Display

The `#[display(...)]` attribute provides a custom display message for variant.
If a custom display is not provided for a wrapped error type like `IoError(std::io::Error)`, it will directly 
delegate its display to the inner type (`std::io::Error`). If it is desired to prevent this, provide a custom 
display message, like in the below example, or add `#[display(opaque)]`. The default display for other
variant types is `ErrorName::VariantName`.
```rust
error_set::error_set! {
    AuthError := {
        #[display("User `{name}` with role `{role}` does not exist")] // Shorthand for `#[display("User `{}` with role `{}` does not exist", name, role)]`
        UserDoesNotExist {
            name: String,
            role: u32,
        },
        #[display("The provided credentials are invalid")]
        InvalidCredentials
    }
    LoginError := {
        #[display("Io Error: {0}")] // Shorthand for `#[display("Io Error: {}", source)]`
        IoError(std::io::Error),
    } || AuthError
}
```

<details>

<summary>Usage</summary>

```rust
error_set::error_set! {
    AuthError := {
        #[display("User `{name}` with role `{role}` does not exist")] // Shorthand for `#[display("User `{}` with role `{}` does not exist", name, role)]`
        UserDoesNotExist {
            name: String,
            role: u32,
        },
        #[display("The provided credentials are invalid")]
        InvalidCredentials
    }
    LoginError := {
        #[display("Io Error: {0}")] // Shorthand for `#[display("Io Error: {}", source)]`
        IoError(std::io::Error),
    } || AuthError
}

fn main() {
    let x: AuthError = AuthError::UserDoesNotExist {
        name: "john".to_string(),
        role: 30,
    };
    assert_eq!(x.to_string(), "User `john` with role `30` does not exist".to_string());
    let y: LoginError = x.into();
    assert_eq!(y.to_string(), "User `john` with role `30` does not exist".to_string());
    let x = AuthError::InvalidCredentials;
    assert_eq!(x.to_string(), "The provided credentials are invalid".to_string());
}
```

</details>

Redeclaring the same variant in a different set and changing the display message, does not
affect the conversion between sets.

### Disabling Automatic Trait Implementations

error_set auto-implements `From`, `Display`, `Debug`, and `Error` for a set. If it is ever desired to disable this. Add `#[skip(..)]` to the set. e.g.
```rust
use std::fmt::{Display, Debug};

error_set::error_set! {
    #[skip(Display,Debug)]
    X := {
        A,
    }
}

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

impl Debug for X {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "X")
    }
}
```
`From` also accepts arguments to only disable certain `From` implementations. e.g.
```rust
error_set::error_set! {
    U := {
        IoError(std::io::Error),
    }
    V := {
        FmtError(std::fmt::Error),
        IoError(std::io::Error),
    }
    #[skip(From(std::io::Error, U))]
    W := V || U
}
```

### Generics

error_set supports generics. e.g.
```rust
use std::fmt::Debug;

error_set::error_set! {
    X<G: Debug> := {
        A {
            a: G
        }
    }
    Y<H: Debug> := {
        B {
            b: H
        }
    }
    Z<T: Debug> := X<T> || Y<T>
}
```
In `Z<T: Debug> := X<T> || Y<T>` `T` will replace `G` in `X` - `X<T: Debug>`. Thus this statement is the
same as writing
```rust
use std::fmt::Debug;

error_set::error_set! {
    // ...

    Z<T: Debug> := {
        A {
            a: T
        },
        B {
            b: T
        }
    }
}
```

### Automatic From's For Boxing

`From` implementations are automatically generated for boxed sources.

```rust
error_set::error_set! {
    Error := {
        Variant(Box<std::io::Error>)
    }
}
```

<details>

  <summary>Generated Code</summary>

```rust
#[derive(Debug)]
pub enum Error {
    Variant(Box<std::io::Error>),
}
#[allow(unused_qualifications)]
impl core::error::Error for Error {
    fn source(&self) -> Option< &(dyn core::error::Error+'static)>{
        match self {
            Error::Variant(source) => source.source(), 
            #[allow(unreachable_patterns)]
            _ => None,
        
            }
    }
}
impl core::fmt::Display for Error {
    #[inline]
    fn fmt(&self,f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match& *self {
            Error::Variant(source) => write!(f,"{}",source),
        
            }
    }
}
impl From<Box<std::io::Error> >for Error {
    fn from(error:Box<std::io::Error>) -> Self {
        Error::Variant(error)
    }
}
impl From<std::io::Error>for Error {
    fn from(error:std::io::Error) -> Self {
        Error::Variant(Box::new(error))
    }
}
```

</details>

### Error Variant Shorthand

The error variant shorthand syntax exists for quickly writing wrapped error enum variants.

```rust
use std::io;

error_set::error_set! {
    Error := {
        (io::Error), // The source type here is used to determine the enum variant name.
        // IoError(io::Error), // This is equivalent to the above syntax. No variant name needed.
    }
}
```

### Error Structs

Error structs are also supported

```rust
error_set::error_set! {
    #[display("This is the display message for the struct. field value {field}")]
    struct ErrorStruct {
        source: std::io::Error, // reserved field name for structs derived from a source.
        field: String,
    }
}
```

<details>

  <summary>Generated Code</summary>

```rust
#[derive(Debug)]
pub struct ErrorStruct {
    source:std::io::Error,field:String,
}
#[allow(unused_qualifications)]
impl core::error::Error for ErrorStruct {
    fn source(&self) -> Option< &(dyn core::error::Error+'static)>{
        Some(&self.source)
    }

    }
impl core::fmt::Display for ErrorStruct {
    #[allow(unused_qualifications)]
    #[inline]
    fn fmt(&self,f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let ErrorStruct {
            source,field
        } =  &self;
        write!(f,"This is the display message for the struct. field value {field}")
    }
}
```

</details>

> Note: An error set can also be represented with the `enum` prefix.
> ```rust
> error_set::error_set! {
>     enum ErrorEnum := {
>         Variant1,
>         Variant2,
>    }
> }
> ```


> By default all structs and enums are `pub`

### Handling Context

Sometimes it is helpful to have more context around one's errors than the information contained by that error. `error_set` recommends using one of the following crates to capture this context.

#### `err_trail`

[err_trail](https://crates.io/crates/err_trail) is a great way to handle context of errors as they propagate through the callstack in a `eros`/`anyhow` like way using logging. See the link for more info.


#### `eros`

[eros](https://github.com/mcmah309/eros) is another great way to handle context as errors propagate through the callstack and capture `Backtrace` with `TracedError`.

```rust
use eros::{Context, IntoTraced, TracedError};
use error_set::error_set;

error_set! {
    OurError := {
        IoError(std::io::Error),
    }

    AnotherError := {
        AnotherErrorVariant,
    } || OurError
}

fn raw_error_result() -> Result<(), std::io::Error> {
    Err(std::io::Error::new(
        std::io::ErrorKind::Other,
        "this is a raw io error",
    ))
}

// `eros::Result<(), std::io::Error>` === `Result<(), TracedError<std::io::Error>>` === `Result<(), TE<std::io::Error>>`
fn traced_error_result() -> eros::Result<(), std::io::Error> {
    raw_error_result()
        // One can wrap the error type with a `TracedError` (aka `TE`) type here.
        // A `Backtrace` may be captured here on `TracedError` creation if enabled.
        .into_traced()
        // Context can be added as the error propagates the callstack
        .context("Here is some context")
}

fn traced_our_error_enum_result1() -> eros::Result<(), OurError> {
    let _ = traced_error_result()
                // `Result<(),TracedError<std::io::Error>>` -> `Result<(),TracedError<OurError>>`
                .into_traced()
                .context("More context")?;
    let _ = raw_error_result()
                // `Result<(),std::io::Error>` -> `Result<(),TracedError<OurError>>`
                .into_traced()
                .context("Different context")?;
    Ok(())
}

fn traced_our_error_enum_result2() -> eros::Result<(), AnotherError> {
    let _ = traced_our_error_enum_result1()
                // `Result<(),TracedError<OurError>>` -> `Result<(),TracedError<AnotherError>>`
                .into_traced()?;
    Ok(())
}

fn main() {
    let error: TracedError<AnotherError> = traced_our_error_enum_result2().unwrap_err();
    assert!(matches!(error.inner(), AnotherError::IoError(_)));
    println!("{:?}", error)
}
```

<details>

  <summary>Output</summary>

```console
this is a raw io error

Context:
        - Here is some context
        - More context

Backtrace:
   0: eros::generic_error::TracedError<T>::new
             at /usr/local/cargo/registry/src/index.crates.io-1949cf8c6b5b557f/eros-0.3.0/src/generic_error.rs:49:24
   1: <E1 as eros::generic_error::IntoTraced<eros::generic_error::TracedError<E2>>>::into_traced
             at /usr/local/cargo/registry/src/index.crates.io-1949cf8c6b5b557f/eros-0.3.0/src/generic_error.rs:369:9
   2: <core::result::Result<S,E1> as eros::generic_error::IntoTraced<core::result::Result<S,eros::generic_error::TracedError<E2>>>>::into_traced::{{closure}}
             at /usr/local/cargo/registry/src/index.crates.io-1949cf8c6b5b557f/eros-0.3.0/src/generic_error.rs:379:28
   3: core::result::Result<T,E>::map_err
             at /usr/local/rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/result.rs:914:27
   4: <core::result::Result<S,E1> as eros::generic_error::IntoTraced<core::result::Result<S,eros::generic_error::TracedError<E2>>>>::into_traced
             at /usr/local/cargo/registry/src/index.crates.io-1949cf8c6b5b557f/eros-0.3.0/src/generic_error.rs:379:14
   5: mod::traced_error::traced_error_result
             at ./tests/mod.rs:1075:28
   6: mod::traced_error::traced_our_error_enum_result1
             at ./tests/mod.rs:1079:17
   7: mod::traced_error::traced_our_error_enum_result2
             at ./tests/mod.rs:1085:17
   8: mod::traced_error::test
             at ./tests/mod.rs:1091:21
   9: mod::traced_error::test::{{closure}}
             at ./tests/mod.rs:1090:14
...
```

</details>

> If one does not need the "context" or "backtrace" functionality provided by `eros`, either feature flag can be disabled.

One should **not** use `eros` like so
```rust
use eros::TracedError;
use error_set::error_set;

error_set! {
    OurError := {
        IoError(TracedError<std::io::Error>), // Nested
    }

    AnotherError := {
        AnotherErrorVariant,
    } || OurError
}
```
Since one would lose tracing operations on `OurError` and `AnotherError`.

### Why Choose `error_set` Over `thiserror` or `anyhow`

`error_set` is a unique approach with some of the same features of `thiserror` and `anyhow`, while solving a few more problems
common to Rust developers.

Like `thiserror`, `error_set` allows you define errors, their display messages, and conversions between errors. However `error_set`
is more maintainable and approximately 50% more concise:

<details>

<summary>example</summary>

```rust,ignore
// thiserror
#[derive(Error)]
enum Error1 {
    a,
    b,
}
#[derive(Error)]
enum Error2 {
    c,
    d,
}
#[derive(Error)]
enum Error3 {
    Error1(#[from] Error1),
    Error2(#[from] Error2),
}

// error_set
error_set! {
    Error1 := {
        a,
        b
    }
    Error2 := {
        c,
        d
    }
    Error3 := Error1 || Error2
    // `Error3` above is equivalent to writing
    // ```
    // Error3 = {
    //    a,
    //    b,
    //    c,
    //    d
    // };
    // ```
}
```

</details>

With `error_set` there is no need to maintain a web of nested wrapped enums (with `#[from]`), since there is no nesting, and all the `From` implementations are automatically generated if one error type is a subset of another.

Like `anyhow`, `error_set` remains open to capturing the context around errors. To accomplish this, it uses the help of [err_trail](#err_trail) or [eros](#eros) crate. See the respective READMEs for more info. However, if your project doesn't require handling specific error types and you just need to propagate errors up the call stack, then `anyhow` or `eros` is likely a good choice for you. It's straightforward and skips the need to define error types altogether.

For libraries and general projects that require precise error handling and differentiation, error management can often become complex and unwieldy
as projects grow. This may even result in "mega enums". `error_set` can help here where others can't.

#### What is a Mega Enum?

A mega enum, or mega error enum, is an enumeration that consolidates various error types into one large enum, whereas the code would be more precise if split into multiple enums.
These often arise due to refactors or developers opting for less intrusive programming approach.
This method can lead to inefficiencies and confusion because it includes error variants that are not relevant in certain scopes. 

##### Example Scenario:

Consider the following functions and their respective error types:

- `func1` can produce errors `a` and `b`, represented by `enum1`.
- `func2` can produce errors `c` and `d`, represented by `enum2`.
- `func3` calls both `func1` and `func2`.

If `func3` does not handle the errors from `func1` and `func2`, it must return an error enum that encompasses variants `a`, `b`, `c`, and `d`. Without a tool like `error_set`, developers might skip defining `enum1` and `enum2` due to the complexity and instead create a mega enum with all possible error variants (`a`, `b`, `c`, `d`). This means that any caller of `func1` or `func2` would have to handle all these cases, even those that are not possible in that specific context. `error_set` being so concise and simple, developers actually want to scope their errors to the correct context and join them when needed with a simple `||` operation. No need to ever think about a web of nested wrapped error types.

##### How `error_set` Simplifies Error Management:

`error_set` allows you to define errors quickly and precisely. Correctly scoping errors is easy and no wrapping of
various error enum types is necessary. Conversions/Propagation up the stack are as simple as `.into()` or `?`.
`error_set` also makes display messages and tracking context easy.
By using `error_set`, your project can maintain clear and precise error definitions, enhancing code readability and maintainability without the tedious process of manually defining and managing error relations.

### no_std

This crate supports `#![no_std]`.