-
Notifications
You must be signed in to change notification settings - Fork 61
/
lib.rs
1494 lines (1405 loc) · 42.9 KB
/
lib.rs
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![deny(missing_docs)]
#![cfg_attr(not(any(feature = "std", test)), no_std)]
#![cfg_attr(feature = "unstable-backtraces-impl-std", feature(backtrace))]
#![cfg_attr(feature = "unstable-core-error", feature(error_in_core))]
#![cfg_attr(
feature = "unstable-provider-api",
feature(error_generic_member_access, provide_any)
)]
#![cfg_attr(feature = "unstable-try-trait", feature(try_trait_v2))]
//! # SNAFU
//!
//! SNAFU is a library to easily generate errors and add information
//! to underlying errors, especially when the same underlying error
//! type can occur in different contexts.
//!
//! For detailed information, please see the [`Snafu`][] macro and the
//! [user's guide](guide).
//!
//! ## Features
//!
//! - [Turnkey errors based on strings](Whatever)
//! - [Custom error types](Snafu)
//! - Including a conversion path from turnkey errors
//! - [Backtraces](Backtrace)
//! - Extension traits for
//! - [`Results`](ResultExt)
//! - [`Options`](OptionExt)
#![cfg_attr(feature = "futures", doc = " - [`Futures`](futures::TryFutureExt)")]
#![cfg_attr(feature = "futures", doc = " - [`Streams`](futures::TryStreamExt)")]
//! - Suitable for libraries and applications
//! - `no_std` compatibility
//! - Generic types and lifetimes
//!
//! ## Quick start
//!
//! If you want to report errors without hassle, start with the
//! [`Whatever`][] type and the [`whatever!`][] macro:
//!
//! ```rust
//! use snafu::{prelude::*, Whatever};
//!
//! fn is_valid_id(id: u16) -> Result<(), Whatever> {
//! if id < 10 {
//! whatever!("ID may not be less than 10, but it was {}", id);
//! }
//! Ok(())
//! }
//! ```
//!
//! You can also use it to wrap any other error:
//!
//! ```rust
//! use snafu::{prelude::*, Whatever};
//!
//! fn read_config_file(path: &str) -> Result<String, Whatever> {
//! std::fs::read_to_string(path)
//! .with_whatever_context(|_| format!("Could not read file {}", path))
//! }
//! ```
//!
//! [`Whatever`][] allows for a short message and tracks a
//! [`Backtrace`][] for every error:
//!
//! ```rust
//! use snafu::{prelude::*, ErrorCompat, Whatever};
//!
//! fn main() {
//! # fn returns_an_error() -> Result<(), Whatever> { Ok(()) }
//! if let Err(e) = returns_an_error() {
//! eprintln!("An error occurred: {}", e);
//! if let Some(bt) = ErrorCompat::backtrace(&e) {
//! # #[cfg(not(feature = "backtraces-impl-backtrace-crate"))]
//! eprintln!("{}", bt);
//! }
//! }
//! }
//! ```
//!
//! ## Custom error types
//!
//! Many projects will hit limitations of the `Whatever` type. When
//! that occurs, it's time to create your own error type by deriving
//! [`Snafu`][]!
//!
//! ### Struct style
//!
//! SNAFU will read your error struct definition and create a *context
//! selector* type (called `InvalidIdSnafu` in this example). These
//! context selectors are used with the [`ensure!`][] macro to provide
//! ergonomic error creation:
//!
//! ```rust
//! use snafu::prelude::*;
//!
//! #[derive(Debug, Snafu)]
//! #[snafu(display("ID may not be less than 10, but it was {id}"))]
//! struct InvalidIdError {
//! id: u16,
//! }
//!
//! fn is_valid_id(id: u16) -> Result<(), InvalidIdError> {
//! ensure!(id >= 10, InvalidIdSnafu { id });
//! Ok(())
//! }
//! ```
//!
//! If you add a `source` field to your error, you can then wrap an
//! underlying error using the [`context`](ResultExt::context)
//! extension method:
//!
//! ```rust
//! use snafu::prelude::*;
//!
//! #[derive(Debug, Snafu)]
//! #[snafu(display("Could not read file {path}"))]
//! struct ConfigFileError {
//! source: std::io::Error,
//! path: String,
//! }
//!
//! fn read_config_file(path: &str) -> Result<String, ConfigFileError> {
//! std::fs::read_to_string(path).context(ConfigFileSnafu { path })
//! }
//! ```
//!
//! ### Enum style
//!
//! While error structs are good for constrained cases, they don't
//! allow for reporting multiple possible kinds of errors at one
//! time. Error enums solve that problem.
//!
//! SNAFU will read your error enum definition and create a *context
//! selector* type for each variant (called `InvalidIdSnafu` in this
//! example). These context selectors are used with the [`ensure!`][]
//! macro to provide ergonomic error creation:
//!
//! ```rust
//! use snafu::prelude::*;
//!
//! #[derive(Debug, Snafu)]
//! enum Error {
//! #[snafu(display("ID may not be less than 10, but it was {id}"))]
//! InvalidId { id: u16 },
//! }
//!
//! fn is_valid_id(id: u16) -> Result<(), Error> {
//! ensure!(id >= 10, InvalidIdSnafu { id });
//! Ok(())
//! }
//! ```
//!
//! If you add a `source` field to a variant, you can then wrap an
//! underlying error using the [`context`](ResultExt::context)
//! extension method:
//!
//! ```rust
//! use snafu::prelude::*;
//!
//! #[derive(Debug, Snafu)]
//! enum Error {
//! #[snafu(display("Could not read file {path}"))]
//! ConfigFile {
//! source: std::io::Error,
//! path: String,
//! },
//! }
//!
//! fn read_config_file(path: &str) -> Result<String, Error> {
//! std::fs::read_to_string(path).context(ConfigFileSnafu { path })
//! }
//! ```
//!
//! You can combine the power of the [`whatever!`][] macro with an
//! enum error type. This is great if you started out with
//! [`Whatever`][] and are moving to a custom error type:
//!
//! ```rust
//! use snafu::prelude::*;
//!
//! #[derive(Debug, Snafu)]
//! enum Error {
//! #[snafu(display("ID may not be less than 10, but it was {id}"))]
//! InvalidId { id: u16 },
//!
//! #[snafu(whatever, display("{message}"))]
//! Whatever {
//! message: String,
//! #[snafu(source(from(Box<dyn std::error::Error>, Some)))]
//! source: Option<Box<dyn std::error::Error>>,
//! },
//! }
//!
//! fn is_valid_id(id: u16) -> Result<(), Error> {
//! ensure!(id >= 10, InvalidIdSnafu { id });
//! whatever!("Just kidding... this function always fails!");
//! Ok(())
//! }
//! ```
//!
//! You may wish to make the type `Send` and/or `Sync`, allowing
//! your error type to be used in multithreaded programs, by changing
//! `dyn std::error::Error` to `dyn std::error::Error + Send + Sync`.
//!
//! ## Next steps
//!
//! Read the documentation for the [`Snafu`][] macro to see all of the
//! capabilities, then read the [user's guide](guide) for deeper
//! understanding.
use core::fmt;
pub mod prelude {
//! Traits and macros used by most projects. Add `use
//! snafu::prelude::*` to your code to quickly get started with
//! SNAFU.
pub use crate::{ensure, OptionExt as _, ResultExt as _};
// https://github.com/rust-lang/rust/issues/89020
doc_comment::doc_comment! {
include_str!("Snafu.md"),
pub use snafu_derive::Snafu;
}
#[cfg(any(feature = "std", test))]
pub use crate::{ensure_whatever, whatever};
#[cfg(feature = "futures")]
pub use crate::futures::{TryFutureExt as _, TryStreamExt as _};
}
#[cfg(all(
not(feature = "backtraces"),
not(feature = "backtraces-impl-backtrace-crate"),
not(feature = "backtraces-impl-std"),
))]
mod backtrace_inert;
#[cfg(all(
not(feature = "backtraces"),
not(feature = "backtraces-impl-backtrace-crate"),
not(feature = "backtraces-impl-std"),
))]
pub use crate::backtrace_inert::*;
#[cfg(all(
feature = "backtraces",
not(feature = "backtraces-impl-backtrace-crate"),
not(feature = "backtraces-impl-std"),
))]
mod backtrace_shim;
#[cfg(all(
feature = "backtraces",
not(feature = "backtraces-impl-backtrace-crate"),
not(feature = "backtraces-impl-std"),
))]
pub use crate::backtrace_shim::*;
#[cfg(any(feature = "std", test))]
mod once_bool;
#[cfg(feature = "backtraces-impl-backtrace-crate")]
pub use backtrace::Backtrace;
#[cfg(feature = "backtraces-impl-std")]
pub use std::backtrace::Backtrace;
#[cfg(feature = "futures")]
pub mod futures;
mod error_chain;
pub use crate::error_chain::*;
mod report;
pub use report::{Report, __InternalExtractErrorType};
doc_comment::doc_comment! {
include_str!("Snafu.md"),
pub use snafu_derive::Snafu;
}
doc_comment::doc_comment! {
include_str!("report.md"),
pub use snafu_derive::report;
}
macro_rules! generate_guide {
(pub mod $name:ident { $($children:tt)* } $($rest:tt)*) => {
generate_guide!(@gen ".", pub mod $name { $($children)* } $($rest)*);
};
(@gen $prefix:expr, ) => {};
(@gen $prefix:expr, pub mod $name:ident; $($rest:tt)*) => {
generate_guide!(@gen $prefix, pub mod $name { } $($rest)*);
};
(@gen $prefix:expr, @code pub mod $name:ident; $($rest:tt)*) => {
#[cfg(feature = "guide")]
pub mod $name;
#[cfg(not(feature = "guide"))]
/// Not currently built; please add the `guide` feature flag.
pub mod $name {}
generate_guide!(@gen $prefix, $($rest)*);
};
(@gen $prefix:expr, pub mod $name:ident { $($children:tt)* } $($rest:tt)*) => {
#[cfg(feature = "guide")]
doc_comment::doc_comment! {
include_str!(concat!($prefix, "/", stringify!($name), ".md")),
pub mod $name {
generate_guide!(@gen concat!($prefix, "/", stringify!($name)), $($children)*);
}
}
#[cfg(not(feature = "guide"))]
/// Not currently built; please add the `guide` feature flag.
pub mod $name {
generate_guide!(@gen concat!($prefix, "/", stringify!($name)), $($children)*);
}
generate_guide!(@gen $prefix, $($rest)*);
};
}
generate_guide! {
pub mod guide {
pub mod comparison {
pub mod failure;
}
pub mod compatibility;
pub mod feature_flags;
pub mod generics;
pub mod opaque;
pub mod philosophy;
pub mod structs;
pub mod what_code_is_generated;
pub mod troubleshooting {
pub mod missing_field_source;
}
pub mod upgrading;
@code pub mod examples;
}
}
doc_comment::doctest!("../README.md", readme_tests);
#[cfg(feature = "unstable-core-error")]
#[doc(hidden)]
pub use core::error::Error;
#[cfg(all(not(feature = "unstable-core-error"), any(feature = "std", test)))]
#[doc(hidden)]
pub use std::error::Error;
#[cfg(not(any(feature = "unstable-core-error", feature = "std", test)))]
mod no_std_error;
#[cfg(not(any(feature = "unstable-core-error", feature = "std", test)))]
#[doc(hidden)]
pub use no_std_error::Error;
/// Ensure a condition is true. If it is not, return from the function
/// with an error.
///
/// ## Examples
///
/// ```rust
/// use snafu::prelude::*;
///
/// #[derive(Debug, Snafu)]
/// enum Error {
/// InvalidUser { user_id: i32 },
/// }
///
/// fn example(user_id: i32) -> Result<(), Error> {
/// ensure!(user_id > 0, InvalidUserSnafu { user_id });
/// // After this point, we know that `user_id` is positive.
/// let user_id = user_id as u32;
/// Ok(())
/// }
/// ```
#[macro_export]
macro_rules! ensure {
($predicate:expr, $context_selector:expr $(,)?) => {
if !$predicate {
return $context_selector
.fail()
.map_err(::core::convert::Into::into);
}
};
}
/// Instantiate and return a stringly-typed error message.
///
/// This can be used with the provided [`Whatever`][] type or with a
/// custom error type that uses `snafu(whatever)`.
///
/// # Without an underlying error
///
/// Provide a format string and any optional arguments. The macro will
/// unconditionally exit the calling function with an error.
///
/// ## Examples
///
/// ```rust
/// use snafu::{Whatever, prelude::*};
///
/// type Result<T, E = Whatever> = std::result::Result<T, E>;
///
/// enum Status {
/// Sleeping,
/// Chilling,
/// Working,
/// }
///
/// # fn stand_up() {}
/// # fn go_downstairs() {}
/// fn do_laundry(status: Status, items: u8) -> Result<()> {
/// match status {
/// Status::Sleeping => whatever!("Cannot launder {items} clothes when I am asleep"),
/// Status::Chilling => {
/// stand_up();
/// go_downstairs();
/// }
/// Status::Working => {
/// go_downstairs();
/// }
/// }
/// Ok(())
/// }
/// ```
///
/// # With an underlying error
///
/// Provide a `Result` as the first argument, followed by a format
/// string and any optional arguments. If the `Result` is an error,
/// the formatted string will be appended to the error and the macro
/// will exit the calling function with an error. If the `Result` is
/// not an error, the macro will evaluate to the `Ok` value of the
/// `Result`.
///
/// ## Examples
///
/// ```rust
/// use snafu::prelude::*;
///
/// #[derive(Debug, Snafu)]
/// #[snafu(whatever, display("Error was: {message}"))]
/// struct Error {
/// message: String,
/// #[snafu(source(from(Box<dyn std::error::Error>, Some)))]
/// source: Option<Box<dyn std::error::Error>>,
/// }
/// type Result<T, E = Error> = std::result::Result<T, E>;
///
/// fn calculate_brightness_factor() -> Result<u8> {
/// let angle = calculate_angle_of_refraction();
/// let angle = whatever!(angle, "There was no angle");
/// Ok(angle * 2)
/// }
///
/// fn calculate_angle_of_refraction() -> Result<u8> {
/// whatever!("The programmer forgot to implement this...");
/// }
/// ```
#[macro_export]
#[cfg(any(feature = "std", test))]
macro_rules! whatever {
($fmt:literal$(, $($arg:expr),* $(,)?)?) => {
return core::result::Result::Err({
$crate::FromString::without_source(
format!($fmt$(, $($arg),*)*),
)
});
};
($source:expr, $fmt:literal$(, $($arg:expr),* $(,)?)*) => {
match $source {
core::result::Result::Ok(v) => v,
core::result::Result::Err(e) => {
return core::result::Result::Err({
$crate::FromString::with_source(
core::convert::Into::into(e),
format!($fmt$(, $($arg),*)*),
)
});
}
}
};
}
/// Ensure a condition is true. If it is not, return a stringly-typed
/// error message.
///
/// This can be used with the provided [`Whatever`][] type or with a
/// custom error type that uses `snafu(whatever)`.
///
/// ## Examples
///
/// ```rust
/// use snafu::prelude::*;
///
/// #[derive(Debug, Snafu)]
/// #[snafu(whatever, display("Error was: {message}"))]
/// struct Error {
/// message: String,
/// }
/// type Result<T, E = Error> = std::result::Result<T, E>;
///
/// fn get_bank_account_balance(account_id: &str) -> Result<u8> {
/// # fn moon_is_rising() -> bool { false }
/// ensure_whatever!(
/// moon_is_rising(),
/// "We are recalibrating the dynamos for account {}, sorry",
/// account_id,
/// );
///
/// Ok(100)
/// }
/// ```
#[macro_export]
#[cfg(any(feature = "std", test))]
macro_rules! ensure_whatever {
($predicate:expr, $fmt:literal$(, $($arg:expr),* $(,)?)?) => {
if !$predicate {
$crate::whatever!($fmt$(, $($arg),*)*);
}
};
}
/// Additions to [`Result`](std::result::Result).
pub trait ResultExt<T, E>: Sized {
/// Extend a [`Result`]'s error with additional context-sensitive information.
///
/// [`Result`]: std::result::Result
///
/// ```rust
/// use snafu::prelude::*;
///
/// #[derive(Debug, Snafu)]
/// enum Error {
/// Authenticating {
/// user_name: String,
/// user_id: i32,
/// source: ApiError,
/// },
/// }
///
/// fn example() -> Result<(), Error> {
/// another_function().context(AuthenticatingSnafu {
/// user_name: "admin",
/// user_id: 42,
/// })?;
/// Ok(())
/// }
///
/// # type ApiError = Box<dyn std::error::Error>;
/// fn another_function() -> Result<i32, ApiError> {
/// /* ... */
/// # Ok(42)
/// }
/// ```
///
/// Note that the context selector will call
/// [`Into::into`](std::convert::Into::into) on each field, so the types
/// are not required to exactly match.
fn context<C, E2>(self, context: C) -> Result<T, E2>
where
C: IntoError<E2, Source = E>,
E2: Error + ErrorCompat;
/// Extend a [`Result`][]'s error with lazily-generated context-sensitive information.
///
/// [`Result`]: std::result::Result
///
/// ```rust
/// use snafu::prelude::*;
///
/// #[derive(Debug, Snafu)]
/// enum Error {
/// Authenticating {
/// user_name: String,
/// user_id: i32,
/// source: ApiError,
/// },
/// }
///
/// fn example() -> Result<(), Error> {
/// another_function().with_context(|_| AuthenticatingSnafu {
/// user_name: "admin".to_string(),
/// user_id: 42,
/// })?;
/// Ok(())
/// }
///
/// # type ApiError = std::io::Error;
/// fn another_function() -> Result<i32, ApiError> {
/// /* ... */
/// # Ok(42)
/// }
/// ```
///
/// Note that this *may not* be needed in many cases because the context
/// selector will call [`Into::into`](std::convert::Into::into) on each
/// field.
fn with_context<F, C, E2>(self, context: F) -> Result<T, E2>
where
F: FnOnce(&mut E) -> C,
C: IntoError<E2, Source = E>,
E2: Error + ErrorCompat;
/// Extend a [`Result`]'s error with information from a string.
///
/// The target error type must implement [`FromString`] by using
/// the
/// [`#[snafu(whatever)]`][Snafu#controlling-stringly-typed-errors]
/// attribute. The premade [`Whatever`] type is also available.
///
/// In many cases, you will want to use
/// [`with_whatever_context`][Self::with_whatever_context] instead
/// as it gives you access to the error and is only called in case
/// of error. This method is best suited for when you have a
/// string literal.
///
/// ```rust
/// use snafu::{prelude::*, Whatever};
///
/// fn example() -> Result<(), Whatever> {
/// std::fs::read_to_string("/this/does/not/exist")
/// .whatever_context("couldn't open the file")?;
/// Ok(())
/// }
///
/// let err = example().unwrap_err();
/// assert_eq!("couldn't open the file", err.to_string());
/// ```
#[cfg(any(feature = "std", test))]
fn whatever_context<S, E2>(self, context: S) -> Result<T, E2>
where
S: Into<String>,
E2: FromString,
E: Into<E2::Source>;
/// Extend a [`Result`]'s error with information from a
/// lazily-generated string.
///
/// The target error type must implement [`FromString`] by using
/// the
/// [`#[snafu(whatever)]`][Snafu#controlling-stringly-typed-errors]
/// attribute. The premade [`Whatever`] type is also available.
///
/// ```rust
/// use snafu::{prelude::*, Whatever};
///
/// fn example() -> Result<(), Whatever> {
/// let filename = "/this/does/not/exist";
/// std::fs::read_to_string(filename)
/// .with_whatever_context(|_| format!("couldn't open the file {}", filename))?;
/// Ok(())
/// }
///
/// let err = example().unwrap_err();
/// assert_eq!(
/// "couldn't open the file /this/does/not/exist",
/// err.to_string(),
/// );
/// ```
///
/// The closure is not called when the `Result` is `Ok`:
///
/// ```rust
/// use snafu::{prelude::*, Whatever};
///
/// let value: std::io::Result<i32> = Ok(42);
/// let result = value.with_whatever_context::<_, String, Whatever>(|_| {
/// panic!("This block will not be evaluated");
/// });
///
/// assert!(result.is_ok());
/// ```
#[cfg(any(feature = "std", test))]
fn with_whatever_context<F, S, E2>(self, context: F) -> Result<T, E2>
where
F: FnOnce(&mut E) -> S,
S: Into<String>,
E2: FromString,
E: Into<E2::Source>;
}
impl<T, E> ResultExt<T, E> for Result<T, E> {
#[cfg_attr(feature = "rust_1_46", track_caller)]
fn context<C, E2>(self, context: C) -> Result<T, E2>
where
C: IntoError<E2, Source = E>,
E2: Error + ErrorCompat,
{
// https://github.com/rust-lang/rust/issues/74042
match self {
Ok(v) => Ok(v),
Err(error) => Err(context.into_error(error)),
}
}
#[cfg_attr(feature = "rust_1_46", track_caller)]
fn with_context<F, C, E2>(self, context: F) -> Result<T, E2>
where
F: FnOnce(&mut E) -> C,
C: IntoError<E2, Source = E>,
E2: Error + ErrorCompat,
{
// https://github.com/rust-lang/rust/issues/74042
match self {
Ok(v) => Ok(v),
Err(mut error) => {
let context = context(&mut error);
Err(context.into_error(error))
}
}
}
#[cfg(any(feature = "std", test))]
#[cfg_attr(feature = "rust_1_46", track_caller)]
fn whatever_context<S, E2>(self, context: S) -> Result<T, E2>
where
S: Into<String>,
E2: FromString,
E: Into<E2::Source>,
{
// https://github.com/rust-lang/rust/issues/74042
match self {
Ok(v) => Ok(v),
Err(error) => Err(FromString::with_source(error.into(), context.into())),
}
}
#[cfg(any(feature = "std", test))]
#[cfg_attr(feature = "rust_1_46", track_caller)]
fn with_whatever_context<F, S, E2>(self, context: F) -> Result<T, E2>
where
F: FnOnce(&mut E) -> S,
S: Into<String>,
E2: FromString,
E: Into<E2::Source>,
{
// https://github.com/rust-lang/rust/issues/74042
match self {
Ok(t) => Ok(t),
Err(mut e) => {
let context = context(&mut e);
Err(FromString::with_source(e.into(), context.into()))
}
}
}
}
/// A temporary error type used when converting an [`Option`][] into a
/// [`Result`][]
///
/// [`Option`]: std::option::Option
/// [`Result`]: std::result::Result
pub struct NoneError;
/// Additions to [`Option`](std::option::Option).
pub trait OptionExt<T>: Sized {
/// Convert an [`Option`][] into a [`Result`][] with additional
/// context-sensitive information.
///
/// [Option]: std::option::Option
/// [Result]: std::option::Result
///
/// ```rust
/// use snafu::prelude::*;
///
/// #[derive(Debug, Snafu)]
/// enum Error {
/// UserLookup { user_id: i32 },
/// }
///
/// fn example(user_id: i32) -> Result<(), Error> {
/// let name = username(user_id).context(UserLookupSnafu { user_id })?;
/// println!("Username was {}", name);
/// Ok(())
/// }
///
/// fn username(user_id: i32) -> Option<String> {
/// /* ... */
/// # None
/// }
/// ```
///
/// Note that the context selector will call
/// [`Into::into`](std::convert::Into::into) on each field, so the types
/// are not required to exactly match.
fn context<C, E>(self, context: C) -> Result<T, E>
where
C: IntoError<E, Source = NoneError>,
E: Error + ErrorCompat;
/// Convert an [`Option`][] into a [`Result`][] with
/// lazily-generated context-sensitive information.
///
/// [`Option`]: std::option::Option
/// [`Result`]: std::result::Result
///
/// ```
/// use snafu::prelude::*;
///
/// #[derive(Debug, Snafu)]
/// enum Error {
/// UserLookup {
/// user_id: i32,
/// previous_ids: Vec<i32>,
/// },
/// }
///
/// fn example(user_id: i32) -> Result<(), Error> {
/// let name = username(user_id).with_context(|| UserLookupSnafu {
/// user_id,
/// previous_ids: Vec::new(),
/// })?;
/// println!("Username was {}", name);
/// Ok(())
/// }
///
/// fn username(user_id: i32) -> Option<String> {
/// /* ... */
/// # None
/// }
/// ```
///
/// Note that this *may not* be needed in many cases because the context
/// selector will call [`Into::into`](std::convert::Into::into) on each
/// field.
fn with_context<F, C, E>(self, context: F) -> Result<T, E>
where
F: FnOnce() -> C,
C: IntoError<E, Source = NoneError>,
E: Error + ErrorCompat;
/// Convert an [`Option`] into a [`Result`] with information
/// from a string.
///
/// The target error type must implement [`FromString`] by using
/// the
/// [`#[snafu(whatever)]`][Snafu#controlling-stringly-typed-errors]
/// attribute. The premade [`Whatever`] type is also available.
///
/// In many cases, you will want to use
/// [`with_whatever_context`][Self::with_whatever_context] instead
/// as it is only called in case of error. This method is best
/// suited for when you have a string literal.
///
/// ```rust
/// use snafu::{prelude::*, Whatever};
///
/// fn example(env_var_name: &str) -> Result<(), Whatever> {
/// std::env::var_os(env_var_name).whatever_context("couldn't get the environment variable")?;
/// Ok(())
/// }
///
/// let err = example("UNDEFINED_ENVIRONMENT_VARIABLE").unwrap_err();
/// assert_eq!("couldn't get the environment variable", err.to_string());
/// ```
#[cfg(any(feature = "std", test))]
fn whatever_context<S, E>(self, context: S) -> Result<T, E>
where
S: Into<String>,
E: FromString;
/// Convert an [`Option`] into a [`Result`][] with information from a
/// lazily-generated string.
///
/// The target error type must implement [`FromString`][] by using
/// the
/// [`#[snafu(whatever)]`][Snafu#controlling-stringly-typed-errors]
/// attribute. The premade [`Whatever`][] type is also available.
///
/// ```rust
/// use snafu::{prelude::*, Whatever};
///
/// fn example(env_var_name: &str) -> Result<(), Whatever> {
/// std::env::var_os(env_var_name).with_whatever_context(|| {
/// format!("couldn't get the environment variable {}", env_var_name)
/// })?;
/// Ok(())
/// }
///
/// let err = example("UNDEFINED_ENVIRONMENT_VARIABLE").unwrap_err();
/// assert_eq!(
/// "couldn't get the environment variable UNDEFINED_ENVIRONMENT_VARIABLE",
/// err.to_string()
/// );
/// ```
///
/// The closure is not called when the `Option` is `Some`:
///
/// ```rust
/// use snafu::{prelude::*, Whatever};
///
/// let value = Some(42);
/// let result = value.with_whatever_context::<_, String, Whatever>(|| {
/// panic!("This block will not be evaluated");
/// });
///
/// assert!(result.is_ok());
/// ```
#[cfg(any(feature = "std", test))]
fn with_whatever_context<F, S, E>(self, context: F) -> Result<T, E>
where
F: FnOnce() -> S,
S: Into<String>,
E: FromString;
}
impl<T> OptionExt<T> for Option<T> {
#[cfg_attr(feature = "rust_1_46", track_caller)]
fn context<C, E>(self, context: C) -> Result<T, E>
where
C: IntoError<E, Source = NoneError>,
E: Error + ErrorCompat,
{
// https://github.com/rust-lang/rust/issues/74042
match self {
Some(v) => Ok(v),
None => Err(context.into_error(NoneError)),
}
}
#[cfg_attr(feature = "rust_1_46", track_caller)]
fn with_context<F, C, E>(self, context: F) -> Result<T, E>
where
F: FnOnce() -> C,
C: IntoError<E, Source = NoneError>,
E: Error + ErrorCompat,
{
// https://github.com/rust-lang/rust/issues/74042
match self {
Some(v) => Ok(v),
None => Err(context().into_error(NoneError)),
}
}
#[cfg(any(feature = "std", test))]
#[cfg_attr(feature = "rust_1_46", track_caller)]
fn whatever_context<S, E>(self, context: S) -> Result<T, E>
where
S: Into<String>,
E: FromString,
{
match self {
Some(v) => Ok(v),
None => Err(FromString::without_source(context.into())),
}
}
#[cfg(any(feature = "std", test))]
#[cfg_attr(feature = "rust_1_46", track_caller)]
fn with_whatever_context<F, S, E>(self, context: F) -> Result<T, E>
where
F: FnOnce() -> S,
S: Into<String>,
E: FromString,
{
match self {
Some(v) => Ok(v),
None => {
let context = context();
Err(FromString::without_source(context.into()))
}
}
}
}
/// Backports changes to the [`Error`](std::error::Error) trait to
/// versions of Rust lacking them.
///
/// It is recommended to always call these methods explicitly so that
/// it is easy to replace usages of this trait when you start
/// supporting a newer version of Rust.
///
/// ```
/// # use snafu::{prelude::*, ErrorCompat};
/// # #[derive(Debug, Snafu)] enum Example {};
/// # fn example(error: Example) {
/// ErrorCompat::backtrace(&error); // Recommended
/// error.backtrace(); // Discouraged
/// # }
/// ```
pub trait ErrorCompat {
/// Returns a [`Backtrace`](Backtrace) that may be printed.
fn backtrace(&self) -> Option<&Backtrace> {
None
}
/// Returns an iterator for traversing the chain of errors,
/// starting with the current error
/// and continuing with recursive calls to `Error::source`.
///
/// To omit the current error and only traverse its sources,
/// use `skip(1)`.
fn iter_chain(&self) -> ChainCompat
where
Self: AsErrorSource,