snafu 0.9.2

An ergonomic error handling library
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
The `Snafu` macro is the entrypoint to defining your own error
types. It is designed to require little configuration for the
recommended and typical usecases while still offering flexibility for
unique situations.

- [`backtrace`]#controlling-backtraces
- [`context`]#controlling-context
- [`crate_root`]#controlling-how-the-snafu-crate-is-resolved
- [`display`]#controlling-display
- [`implicit`]#controlling-implicitly-generated-data
- [`module`]#placing-context-selectors-in-modules
- [`provide`]#providing-data-beyond-the-error-trait
- [`source`]#controlling-error-sources
- [`transparent`]#delegating-to-the-underlying-error
- [`visibility`]#controlling-visibility
- [`whatever`]#controlling-stringly-typed-errors

## Attribute cheat sheet

Use this as a quick reminder of what each attribute can do and where
it is valid. Detailed information on each attribute is below.

### Enum

| Option (inside `#[snafu(...)]`) | Description                                                                                                 |
|---------------------------------|-------------------------------------------------------------------------------------------------------------|
| `visibility(V)`                 | Sets the default visibility of the generated context selectors to `V` (e.g. `pub`)                          |
| `module`                        | Puts the generated context selectors into a module (module name is the enum name converted to `snake_case`) |
| `module(N)`                     | Same as above, but with the module named `N` instead                                                        |
| `context(suffix(N))`            | Changes the default context selector suffix from `Snafu` to `N`                                             |
| `crate_root(C)`                 | Generated code refers to a crate named `C` instead of the default `snafu`                                   |

### Enum variant or struct

| Option (inside `#[snafu(...)]`) | Description                                                                                                                                                      |
|---------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `display("{field:?}: {}", foo)` | Sets the display implementation for this error variant using `format_args!` syntax. If this is omitted, the default is `"VariantName"                            |
| `context(false)`                | Skips creation of the context selector, implements `From` for the mandatory source error                                                                         |
| `context(suffix(N))`            | Changes the suffix of the generated context selector to `N`                                                                                                      |
| `context(suffix(false))`        | No suffix for the generated context selector                                                                                                                     |
| `context(name(N))`              | The generated context selector will be named `N`                                                                                                                 |
| `transparent`                   | Delegates `Display` and `Error::source` to this error's source, implies `context(false)`                                                                         |
| `visibility(v)`                 | Sets the visibility of the generated context selector to `v` (e.g. `pub`)                                                                                        |
| `visibility`                    | Resets visibility back to private                                                                                                                                |
| `provide(flags, type => expr)`  | Provides the type using the `expr` with the optional flags                                                                                                       |
| `whatever`                      | Stringly-typed error. Message field must be called `message`. Source optional, but if present must be of a specific [format]#controlling-stringly-typed-errors |

### Context fields

| Option (inside `#[snafu(...)]`) | Description                                                                                             |
|---------------------------------|---------------------------------------------------------------------------------------------------------|
| `source`                        | Marks a field as the source error (even if not called `source`)                                         |
| `source(from(type, transform))` | Marks a field as the source error and converts from `type` to the field type by calling `transform`     |
| `source(from(generic))`         | Marks a field as the source error and converts from any type to the field type by calling ``Into::into` |
| `source(from(exact))`           | Marks a field as the source error and performs no conversion to the field type                          |
| `source(false)`                 | Marks a field that is named `source` as a regular field                                                 |
| `backtrace`                     | Marks a field as backtrace (even if not called `backtrace`)                                             |
| `backtrace(false)`              | Marks a field that is named `backtrace` as a regular field                                              |
| `implicit`                      | Marks a field as implicit (Type needs to implement [`GenerateImplicitData`][])                          |
| `provide`                       | Marks a field as providing a reference to the type                                                      |

## Controlling `Display`

You can specify how the `Display` trait will be implemented for each
variant. The argument is a format string and the arguments. All of the
fields of the variant will be available and you can call methods on
them, such as `filename.display()`. As an extension to the current
format string capabilities, a shorthand is available for named
arguments that match a field.

**Example**

```rust
# use snafu::prelude::*;
#[derive(Debug, Snafu)]
enum Error {
    #[snafu(display("{username} may not log in until they pay USD {amount:E}"))]
    UserMustPayForService { username: String, amount: f32 },
}
fn main() {
    assert_eq!(
        UserMustPayForServiceSnafu {
            username: "Stefani",
            amount: 1_000_000.0,
        }
        .build()
        .to_string(),
        "Stefani may not log in until they pay USD 1E6",
    );
}
```

### The default `Display` implementation

It is recommended that you provide a value for `snafu(display)`, but
if it is omitted, the summary of the documentation comment will be
used. If that is not present, the name of the variant will be used.

```rust
# use snafu::prelude::*;
#[derive(Debug, Snafu)]
enum Error {
    /// No user available.
    /// You may need to specify one.
    MissingUser,
    MissingPassword,
}

fn main() {
    assert_eq!(
        MissingUserSnafu.build().to_string(),
        "No user available. You may need to specify one.",
    );
    assert_eq!(MissingPasswordSnafu.build().to_string(), "MissingPassword");
}
```

## Controlling context

### Changing the context selector suffix

When context selectors are generated, any `Error` suffix is removed
and the suffix `Snafu` is added by default. If you'd prefer a
different suffix, such as `Ctx` or `Context`, you can specify that
with `#[snafu(context(suffix(SomeIdentifier)))]`. If you'd like to
disable the suffix entirely, you can use
`#[snafu(context(suffix(false)))]`.

**Example**

```rust
# use snafu::prelude::*;
#
#[derive(Debug, Snafu)]
enum Error {
    UsesTheDefaultSuffixError,

    #[snafu(context(suffix(Ctx)))]
    HasAnotherSuffix,

    #[snafu(context(suffix(false)))]
    DoesNotHaveASuffix,
}

fn my_code() -> Result<(), Error> {
    UsesTheDefaultSuffixSnafu.fail()?;

    HasAnotherSuffixCtx.fail()?;

    DoesNotHaveASuffix.fail()?;

    Ok(())
}
```

`#[snafu(context(suffix))]` can be specified on an enum as the default
suffix for variants of the enum. In that case, if you wish to have one
variant with a suffix, you will need to express it explicitly with
`#[snafu(context(suffix(SomeIdentifier)))]`.

### Changing the context selector name

If you'd prefer the context selector to have a completely distinct
name from the original, you may specify the exact name with
`#[snafu(context(name(SomeIdentifier)))]`.

**Example**

```rust
# use snafu::prelude::*;
#
#[derive(Debug, Snafu)]
enum Error {
    #[snafu(context(name(ButThisNameInstead)))]
    ItIsNotThisName,
}

fn my_code() -> Result<(), Error> {
    ButThisNameInstead.fail()?;

    Ok(())
}
```

### Disabling the context selector

Sometimes, an underlying error can only occur in exactly one context
and there's no additional information that can be provided to the
caller. In these cases, you can use `#[snafu(context(false))]` to
indicate that no context selector should be created. This allows using
the `?` operator directly on the underlying error.

Please think about your end users before making liberal use of this
feature. Adding context to an error is often what distinguishes an
actionable error from a frustrating one.

**Example**

```rust
# use snafu::prelude::*;
#
#[derive(Debug, Snafu)]
enum Error {
    #[snafu(context(false))]
    NeedsNoIntroduction { source: VeryUniqueError },
}

fn my_code() -> Result<i32, Error> {
    let val = do_something_unique()?;
    Ok(val + 10)
}

# #[derive(Debug, Snafu)]
# enum VeryUniqueError {}
fn do_something_unique() -> Result<i32, VeryUniqueError> {
    // ...
#    Ok(42)
}
```

### Delegating to the underlying error

When creating a contextful error you might want to reuse it in
multiple places - composing different error types is idiomatic, after
all. This can lead to unwanted nesting as both the enum variant and
the source error are visible in the source chain and in autogenerated
`Display` implementations.

You can use `#[snafu(transparent)]` to delegate the `Display` and
`Error::source` implementations to the underlying error instead,
effectively removing the wrapping error variant from the logical error
chain. That way you get both the maintenance and logical benefits of
composing errors, without the redundant nesting.

`#[snafu(transparent)]` implies `#[snafu(context(false))]`. Because
`#[snafu(transparent)]` errors delegate `Display` to the source error,
you cannot use `#[snafu(display(...))]` on them.

**Example**

This example allows adding or removing users from groups. The group ID
is passed as a raw integer which needs to be validated first.

Since adding and removing users have distinct error types, there's
nothing useful to say in addition to the validation error message, so
this is a good time to use `#[snafu(transparent)]`.

```rust
# use snafu::prelude::*;
#
fn add_to_group(group: u32, user: &str) -> Result<(), AddToGroupError> {
    let group = GroupId::validate(group)?;
    // ... do useful operation
    Ok(())
}

fn remove_from_group(group: u32, user: &str) -> Result<(), RemoveFromGroupError> {
    let group = GroupId::validate(group)?;
    // ... do useful operation
    Ok(())
}

#[derive(Debug, Snafu)]
enum AddToGroupError {
    #[snafu(transparent)]
    Group { source: GroupIdError },

    // ... other failure conditions
}

#[derive(Debug, Snafu)]
enum RemoveFromGroupError {
    #[snafu(transparent)]
    Group { source: GroupIdError },

    // ... other failure conditions
}

#[derive(Debug)]
struct GroupId(u32);

impl GroupId {
    fn validate(id: u32) -> Result<Self, GroupIdError> {
        // ... perform validation
#       GroupIdSnafu { id }.fail()
    }
}

#[derive(Debug, Snafu)]
#[snafu(display("Group ID {id} does not exist"))]
struct GroupIdError { id: u32 };
```

## Controlling visibility

By default, each of the context selectors and their inherent
methods will be private. It is our opinion that each module should
have one or more error types that are scoped to that module,
reducing the need to deal with unrelated errors when matching and
increasing cohesiveness.

If you need to access the context selectors from outside of their
module, you can use the `#[snafu(visibility)]` attribute. This can
be applied to the error type as a default visibility or to
specific context selectors.

There are multiple forms of the attribute:

- `#[snafu(visibility(X))]`

  `X` is a normal Rust visibility modifier (`pub`, `pub(crate)`,
  `pub(in some::path)`, etc.).

- `#[snafu(visibility)]` will reset back to private visibility.

```
# use snafu::prelude::*;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))] // Sets the default visibility for these context selectors
pub(crate) enum Error {
    IsPubCrate, // Uses the default
    #[snafu(visibility)]
    IsPrivate, // Will be private
}
```

It should be noted that API stability of context selectors is not
guaranteed. Therefore, exporting them in a crate's public API
could cause semver breakage for such crates, should SNAFU internals
change.

## Placing context selectors in modules

When you have multiple error enums that would generate conflicting
context selectors, you can choose to place the context selectors into
a module using `snafu(module)`:

```rust
use snafu::prelude::*;

#[derive(Debug, Snafu)]
#[snafu(module)]
enum ReadError {
    Opening,
}

fn example() -> Result<(), ReadError> {
    read_error::OpeningSnafu.fail()
}

#[derive(Debug, Snafu)]
enum WriteError {
    Opening, // Would conflict if `snafu(module)` was not used above.
}
# // https://github.com/rust-lang/rust/issues/83583
# fn main() {}
```

By default, the module name will be the `snake_case` equivalent of the
enum name. You can override the default by providing an argument to
`#[snafu(module(...))]`:

```rust
use snafu::prelude::*;

#[derive(Debug, Snafu)]
#[snafu(module(read))]
enum ReadError {
    Opening,
}

fn example() -> Result<(), ReadError> {
    read::OpeningSnafu.fail()
}
# // https://github.com/rust-lang/rust/issues/83583
# fn main() {}
```

As placing the context selectors in a module naturally namespaces
them, you may wish to combine this option with
`#[snafu(context(suffix(false)))]`:

```rust
use snafu::prelude::*;

#[derive(Debug, Snafu)]
#[snafu(module, context(suffix(false)))]
enum ReadError {
    Opening,
}

fn example() -> Result<(), ReadError> {
    read_error::Opening.fail()
}
# // https://github.com/rust-lang/rust/issues/83583
# fn main() {}
```

The generated module starts with `use super::*`, so any types or
traits used by the context selectors need to be in scope — complicated
paths may need to be simplified or made absolute.

By default, the visibility of the generated module will be private
while the context selectors inside will be `pub(super)`. Using
[`#[snafu(visibility)]`](#controlling-visibility) to control the
visibility will change the visibility of *both* the module and the
context selectors.

## Controlling error sources

### Selecting the source field

If your error enum variant contains other errors but the field
cannot be named `source`, or if it contains a field named `source`
which is not actually an error, you can use `#[snafu(source)]` to
indicate if a field is an underlying cause or not:

```rust
# mod another {
#     use snafu::prelude::*;
#     #[derive(Debug, Snafu)]
#     pub enum Error {}
# }
# use snafu::prelude::*;
#[derive(Debug, Snafu)]
enum Error {
    SourceIsNotAnError {
        #[snafu(source(false))]
        source: String,
    },

    CauseIsAnError {
        #[snafu(source)]
        cause: another::Error,
    },
}
```

### Transforming the source

If your error type contains an underlying cause that needs to be
transformed, you can use `#[snafu(source(from(...)))]`. This takes
two arguments: the real type and an expression to transform from
that type to the type held by the error.

```rust
# mod another {
#     use snafu::prelude::*;
#     #[derive(Debug, Snafu)]
#     pub enum Error {}
# }
# use snafu::prelude::*;
#[derive(Debug, Snafu)]
enum Error {
    SourceNeedsToBeBoxed {
        #[snafu(source(from(another::Error, Box::new)))]
        source: Box<another::Error>,
    },
}

#[derive(Debug, Snafu)]
#[snafu(source(from(Error, Box::new)))]
struct ApiError(Box<Error>);
```

Note: If you specify `#[snafu(source(from(...)))]` then the field will
be treated as a source, even if it's not named "source" - in other
words, this option implies `#[snafu(source)]`.

#### From an arbitrary type

If you have an error that does not create a context selector, such as
an opaque error or `context(false)` error, you may use
`#[snafu(source(from(generic)))]` to create the wrapping error from
any type that can be converted [`into`](Into::into) the wrapped error.

```rust
# use snafu::prelude::*;
#[derive(Debug, Snafu)]
struct InternalError {
    code: i32,
}

impl From<i32> for InternalError {
    fn from(code: i32) -> Self {
        Self { code }
    }
}

#[derive(Debug, Snafu)]
#[snafu(context(false))]
struct Error {
    #[snafu(source(from(generic)))]
    source: InternalError,
}

pub fn usage() -> Result<(), Error> {
    let code: Result<(), i32> = Err(42);

    // Converts the error type from `i32` to `InternalError` to `Error`.
    code?;

    Ok(())
}
```

Using this option with errors that create context selectors will
result in an error.

Note: If you specify `#[snafu(source(from(generic)))]` then the field
will be treated as a source, even if it's not named "source" - in
other words, this option implies `#[snafu(source)]`.

#### Disabling source transformation

`#[snafu(source(from(exact)))]` can be used to explicitly disable
source transformation.

Note: If you specify `#[snafu(source(from(exact)))]` then the field
will be treated as a source, even if it's not named "source" - in
other words, this option implies `#[snafu(source)]`.

## Controlling backtraces

If your error enum variant contains a backtrace but the field
cannot be named `backtrace`, or if it contains a field named
`backtrace` which is not actually a backtrace, you can use
`#[snafu(backtrace)]` to indicate if a field is actually a
 backtrace or not:

```rust
# use snafu::{prelude::*, Backtrace};
#[derive(Debug, Snafu)]
enum Error {
    BacktraceIsNotABacktrace {
        #[snafu(backtrace(false))]
        backtrace: bool,
    },

    TraceIsABacktrace {
        #[snafu(backtrace)]
        trace: Backtrace,
    },
}
```

If your error contains other SNAFU errors which can report
backtraces, you may wish to delegate returning a backtrace to
those errors. To specify this, use `#[snafu(backtrace)]` on the
source field representing the other error:

```rust
# mod another {
#     use snafu::prelude::*;
#     #[derive(Debug, Snafu)]
#     pub enum Error {}
# }
# use snafu::prelude::*;
#[derive(Debug, Snafu)]
enum Error {
    MyError {
        #[snafu(backtrace)]
        source: another::Error,
    },
}
```

## Providing data beyond the `Error` trait

When the [`unstable-provider-api` feature flag][] is enabled, errors
will implement the [`Error::provide` method][Error::provide]. This
allows arbitrary data to be associated with an error instance,
expanding the abilities of the receiver of the error:

```rust,ignore
use core::error;
use snafu::prelude::*;

#[derive(Debug)]
struct UserId(u8);

#[derive(Debug, Snafu)]
enum ApiError {
    Login {
        #[snafu(provide)]
        user_id: UserId,
    },

    Logout {
        #[snafu(provide)]
        user_id: UserId,
    },

    NetworkUnreachable { source: std::io::Error },
}

let e = LoginSnafu { user_id: UserId(0) }.build();
match error::request_ref::<UserId>(&e) {
    // Present when ApiError::Login or ApiError::Logout
    Some(UserId(user_id)) => {
        println!("{user_id} experienced an error");
    }
    // Absent when ApiError::NetworkUnreachable
    None => {
        println!("An error occurred for an unknown user");
    }
}
```

This attribute may be used even when the [`unstable-provider-api`
feature flag][] is not enabled. In that case, the attribute will be
parsed but no code will be generated, allowing library authors to
provide data to consumers willing to use nightly without losing
support for stable Rust.

[`unstable-provider-api` feature flag]: guide::feature_flags#unstable-provider-api

### Automatically provided data

By default, `backtrace` fields are exposed to the provider API:

```rust,ignore
use core::error;
use snafu::prelude::*;

#[derive(Debug, Snafu)]
struct AuthorizationError {
    backtrace: snafu::Backtrace,
}

let e = AuthorizationSnafu.build();

// We can get the backtrace
error::request_ref::<snafu::Backtrace>(&e).expect("Must have a backtrace");
```

The backtrace from the current error will be provided. Most usages of
a backtrace will want to walk the error chain to find the deepest
possible backtrace:

```rust,ignore
use core::error;
use snafu::{prelude::*, ErrorCompat, IntoError};

#[derive(Debug, Snafu)]
struct InnerError {
    backtrace: snafu::Backtrace,
}

#[derive(Debug, Snafu)]
struct OuterError {
    source: InnerError,
    backtrace: snafu::Backtrace,
}

let e = OuterSnafu.into_error(InnerSnafu.build());

// Get the deepest backtrace
ErrorCompat::iter_chain(&e)
    .filter_map(error::request_ref::<snafu::Backtrace>)
    .last()
    .expect("Must have a backtrace");
```

### Manually provided data

When used on a field, the `#[snafu(provide)]` attribute will expose
that field as a reference, allowing it to be used with
[`request_ref`][]. For more control, the `#[snafu(provide)]` attribute
can be placed on the error struct or enum variant. In this location,
you supply a type and an expression that will generate that type:

```rust,ignore
use core::error;
use snafu::prelude::*;

#[derive(Debug, PartialEq)]
struct HttpCode(u16);

const HTTP_NOT_FOUND: HttpCode = HttpCode(404);

#[derive(Debug, Snafu)]
#[snafu(provide(HttpCode => HTTP_NOT_FOUND))]
struct WebserverError;

let e = WebserverError;
assert_eq!(Some(HTTP_NOT_FOUND), error::request_value::<HttpCode>(&e));
```

The expression may access any field of the error as well as `self`:

```rust,ignore
use core::error;
use snafu::prelude::*;

#[derive(Debug, PartialEq)]
struct Summation(u8);

#[derive(Debug, Snafu)]
#[snafu(provide(Summation => Summation(left_side + right_side)))]
struct AdditionError {
    left_side: u8,
    right_side: u8,
}

let e = AdditionSnafu {
    left_side: 1,
    right_side: 2,
}
.build();
assert_eq!(Some(Summation(3)), error::request_value::<Summation>(&e));
```

### Configuring how data is provided

You may also provide a number of optional flags that control how the
provided data will be exposed. These flags may be combined as required
and may be provided in any order.

#### `provide(ref, ...`

[provide-flag-ref]: #provideref-

Provides the data as a reference instead of as a value. The reference
must live as long as the error itself.

```rust,ignore
use core::error;
use snafu::prelude::*;

#[derive(Debug, Snafu)]
#[snafu(provide(ref, str => name))]
struct RefFlagExampleError {
    name: String,
}

let e = RefFlagExampleSnafu { name: "alice" }.build();

assert_eq!(Some("alice"), error::request_ref::<str>(&e));
```

#### `provide(opt, ...`

[provide-flag-opt]: #provideopt-

If the data being provided is an `Option<T>`, the `opt` flag will
flatten the data, allowing you to request `T` instead of `Option<T>`.

```rust,ignore
use core::error;
use snafu::prelude::*;

#[derive(Debug, Snafu)]
#[snafu(provide(opt, char => char::from_u32(*char_code)))]
struct OptFlagExampleError {
    char_code: u32,
}

let e = OptFlagExampleSnafu { char_code: b'x' }.build();

assert_eq!(Some('x'), error::request_value::<char>(&e));
```

### API stability concerns

For public errors, it's a good idea to explicitly state your intended
stability guarantees around provided values. Some consumers may expect
that if your error type returns data via the provider API in one
situation, it will continue to do so in future SemVer-compatible
releases. However, doing so can greatly hinder your ability to
refactor your code.

Stating your guarantees is especially useful for opaque errors, which
will expose all the provided data from the inner error type.

[`Error::provide`]: https://doc.rust-lang.org/nightly/core/error/trait.Error.html#method.provide
[`request_ref`]: https://doc.rust-lang.org/nightly/std/error/fn.request_ref.html

## Controlling implicitly generated data

Sometimes, you can capture contextual error data without needing any
arguments. [Backtraces][`Backtrace`] are a common example, but other
global information like the current time or thread ID could also be
useful. In these cases, you can use `#[snafu(implicit)]` on a field
that implements [`GenerateImplicitData`] to remove the need to specify
that data at error construction time:

```rust
use snafu::prelude::*;
use std::time::Instant;

#[derive(Debug, PartialEq)]
struct Timestamp(Instant);

impl snafu::GenerateImplicitData for Timestamp {
    fn generate() -> Self {
        Timestamp(Instant::now())
    }
}

#[derive(Debug, Snafu)]
struct RequestError {
    #[snafu(implicit)]
    timestamp: Timestamp,
}

fn do_request() -> Result<(), RequestError> {
    // ...
    # let request_count = 10;
    ensure!(request_count < 3, RequestSnafu);

    Ok(())
}
```

You can use `#[snafu(implicit(false))]` if a field is incorrectly
automatically identified as containing implicit data.

## Controlling stringly-typed errors

This allows your custom error type to behave like the [`Whatever`][]
error type. Since it is your type, you can implement additional
methods or traits. When placed on a struct or enum variant, you will
be able to use the type with the [`whatever!`][] macro as well as
`whatever_context` methods, such as [`ResultExt::whatever_context`][].

```rust
# use snafu::prelude::*;
#[derive(Debug, Snafu)]
enum Error {
    SpecificError {
        username: String,
    },

    #[snafu(whatever, display("{message}"))]
    GenericError {
        message: String,

        // Having a `source` is optional, but if it is present, it must
        // have this specific attribute and type:
        #[snafu(source(from(Box<dyn std::error::Error>, Some)))]
        source: Option<Box<dyn std::error::Error>>,
    },
}
```

## Controlling how the `snafu` crate is resolved

If the `snafu` crate is not called `snafu` for some reason, you can
use `#[snafu(crate_root)]` to instruct the macro how to find the crate
root:

```rust
# use snafu as my_custom_naming_of_snafu;
use my_custom_naming_of_snafu::Snafu;

#[derive(Debug, Snafu)]
#[snafu(crate_root(my_custom_naming_of_snafu))]
enum Error {
    SomeFailureMode,
}

#[derive(Debug, Snafu)]
#[snafu(crate_root(my_custom_naming_of_snafu))]
struct ApiError(Error);
```