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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
#![deny(missing_docs)]
#![cfg_attr(not(any(feature = "std", test)), no_std)]
#![cfg_attr(feature = "unstable-backtraces-impl-std", feature(backtrace))]
//! # 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 = "unstable-backtraces-impl-std"),
))]
mod backtrace_inert;
#[cfg(all(
not(feature = "backtraces"),
not(feature = "backtraces-impl-backtrace-crate"),
not(feature = "unstable-backtraces-impl-std"),
))]
pub use crate::backtrace_inert::*;
#[cfg(all(
feature = "backtraces",
not(feature = "backtraces-impl-backtrace-crate"),
not(feature = "unstable-backtraces-impl-std"),
))]
mod backtrace_shim;
#[cfg(all(
feature = "backtraces",
not(feature = "backtraces-impl-backtrace-crate"),
not(feature = "unstable-backtraces-impl-std"),
))]
pub use crate::backtrace_shim::*;
#[cfg(feature = "backtraces-impl-backtrace-crate")]
pub use backtrace::Backtrace;
#[cfg(feature = "unstable-backtraces-impl-std")]
pub use std::backtrace::Backtrace;
#[cfg(feature = "futures")]
pub mod futures;
#[cfg(feature = "std")]
mod error_chain;
#[cfg(feature = "std")]
pub use crate::error_chain::*;
doc_comment::doc_comment! {
include_str!("Snafu.md"),
pub use snafu_derive::Snafu;
}
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(any(feature = "std", test))]
#[doc(hidden)]
pub use std::error::Error;
#[cfg(not(any(feature = "std", test)))]
mod no_std_error;
#[cfg(not(any(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 exist 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)`.
#[cfg(feature = "std")]
fn iter_chain(&self) -> ChainCompat
where
Self: AsErrorSource,
{
ChainCompat::new(self.as_error_source())
}
}
impl<'a, E> ErrorCompat for &'a E
where
E: ErrorCompat,
{
fn backtrace(&self) -> Option<&Backtrace> {
(**self).backtrace()
}
}
#[cfg(any(feature = "std", test))]
impl<E> ErrorCompat for Box<E>
where
E: ErrorCompat,
{
fn backtrace(&self) -> Option<&Backtrace> {
(**self).backtrace()
}
}
/// Converts the receiver into an [`Error`][] trait object, suitable
/// for use in [`Error::source`][].
///
/// It is expected that most users of SNAFU will not directly interact
/// with this trait.
///
/// [`Error`]: std::error::Error
/// [`Error::source`]: std::error::Error::source
//
// Given an error enum with multiple types of underlying causes:
//
// ```rust
// enum Error {
// BoxTraitObjectSendSync(Box<dyn error::Error + Send + Sync + 'static>),
// BoxTraitObject(Box<dyn error::Error + 'static>),
// Boxed(Box<io::Error>),
// Unboxed(io::Error),
// }
// ```
//
// This trait provides the answer to what consistent expression can go
// in each match arm:
//
// ```rust
// impl error::Error for Error {
// fn source(&self) -> Option<&(dyn error::Error + 'static)> {
// use Error::*;
//
// let v = match *self {
// BoxTraitObjectSendSync(ref e) => ...,
// BoxTraitObject(ref e) => ...,
// Boxed(ref e) => ...,
// Unboxed(ref e) => ...,
// };
//
// Some(v)
// }
// }
//
// Existing methods like returning `e`, `&**e`, `Borrow::borrow(e)`,
// `Deref::deref(e)`, and `AsRef::as_ref(e)` do not work for various
// reasons.
pub trait AsErrorSource {
/// For maximum effectiveness, this needs to be called as a method
/// to benefit from Rust's automatic dereferencing of method
/// receivers.
fn as_error_source(&self) -> &(dyn Error + 'static);
}
impl AsErrorSource for dyn Error + 'static {
fn as_error_source(&self) -> &(dyn Error + 'static) {
self
}
}
impl AsErrorSource for dyn Error + Send + 'static {
fn as_error_source(&self) -> &(dyn Error + 'static) {
self
}
}
impl AsErrorSource for dyn Error + Sync + 'static {
fn as_error_source(&self) -> &(dyn Error + 'static) {
self
}
}
impl AsErrorSource for dyn Error + Send + Sync + 'static {
fn as_error_source(&self) -> &(dyn Error + 'static) {
self
}
}
impl<T> AsErrorSource for T
where
T: Error + 'static,
{
fn as_error_source(&self) -> &(dyn Error + 'static) {
self
}
}
/// Combines an underlying error with additional information
/// about the error.
///
/// It is expected that most users of SNAFU will not directly interact
/// with this trait.
pub trait IntoError<E>
where
E: Error + ErrorCompat,
{
/// The underlying error
type Source;
/// Combine the information to produce the error
fn into_error(self, source: Self::Source) -> E;
}
/// Takes a string message and builds the corresponding error.
///
/// It is expected that most users of SNAFU will not directly interact
/// with this trait.
#[cfg(any(feature = "std", test))]
pub trait FromString {
/// The underlying error
type Source;
/// Create a brand new error from the given string
fn without_source(message: String) -> Self;
/// Wrap an existing error with the given string
fn with_source(source: Self::Source, message: String) -> Self;
}
/// Construct data to be included as part of an error. The data must
/// require no arguments to be created.
pub trait GenerateImplicitData {
/// Build the data.
fn generate() -> Self;
}
/// View a backtrace-like value as an optional backtrace.
pub trait AsBacktrace {
/// Retrieve the optional backtrace
fn as_backtrace(&self) -> Option<&Backtrace>;
}
/// Only create a backtrace when an environment variable is set.
///
/// This looks first for the value of `RUST_LIB_BACKTRACE` then
/// `RUST_BACKTRACE`. If the value is set to `1`, backtraces will be
/// enabled.
///
/// This value will be tested only once per program execution;
/// changing the environment variable after it has been checked will
/// have no effect.
#[cfg(any(feature = "std", test))]
impl GenerateImplicitData for Option<Backtrace> {
fn generate() -> Self {
use std::env;
use std::sync::{
atomic::{AtomicBool, Ordering},
Once,
};
static START: Once = Once::new();
static ENABLED: AtomicBool = AtomicBool::new(false);
START.call_once(|| {
// TODO: What values count as "true"?
let enabled = env::var_os("RUST_LIB_BACKTRACE")
.or_else(|| env::var_os("RUST_BACKTRACE"))
.map_or(false, |v| v == "1");
ENABLED.store(enabled, Ordering::SeqCst);
});
if ENABLED.load(Ordering::SeqCst) {
Some(Backtrace::generate())
} else {
None
}
}
}
#[cfg(any(feature = "std", test))]
impl AsBacktrace for Option<Backtrace> {
fn as_backtrace(&self) -> Option<&Backtrace> {
self.as_ref()
}
}
#[cfg(feature = "backtraces-impl-backtrace-crate")]
impl GenerateImplicitData for Backtrace {
fn generate() -> Self {
Backtrace::new()
}
}
#[cfg(feature = "backtraces-impl-backtrace-crate")]
impl AsBacktrace for Backtrace {
fn as_backtrace(&self) -> Option<&Backtrace> {
Some(self)
}
}
#[cfg(feature = "unstable-backtraces-impl-std")]
impl GenerateImplicitData for Backtrace {
fn generate() -> Self {
Backtrace::force_capture()
}
}
#[cfg(feature = "unstable-backtraces-impl-std")]
impl AsBacktrace for Backtrace {
fn as_backtrace(&self) -> Option<&Backtrace> {
Some(self)
}
}
/// The source code location where the error was reported.
///
/// To use it, add a field `location: Location` to your error. This
/// will automatically register it as [implicitly generated
/// data][implicit].
///
/// [implicit]: Snafu#controlling-implicitly-generated-data
///
/// ## Limitations
///
/// ### Rust 1.46
///
/// You need to enable the [`rust_1_46` feature flag][flag] for
/// implicit location capture. If you cannot enable that, you can
/// still use the [`location!`] macro at the expense of more typing.
///
/// [flag]: guide::compatibility#rust_1_46
///
/// ### Disabled context selectors
///
/// If you have [disabled the context selector][disabled], SNAFU will
/// not be able to capture an accurate location.
///
/// As a workaround, re-enable the context selector.
///
/// [disabled]: Snafu#disabling-the-context-selector
///
/// ### Asynchronous code
///
/// When using SNAFU's
#[cfg_attr(feature = "futures", doc = " [`TryFutureExt`][futures::TryFutureExt]")]
#[cfg_attr(not(feature = "futures"), doc = " `TryFutureExt`")]
/// or
#[cfg_attr(feature = "futures", doc = " [`TryStreamExt`][futures::TryStreamExt]")]
#[cfg_attr(not(feature = "futures"), doc = " `TryStreamExt`")]
/// extension traits, the automatically captured location will
/// correspond to where the future or stream was **polled**, not where
/// it was created. Additionally, many `Future` or `Stream`
/// combinators do not forward the caller's location to their
/// closures, causing the recorded location to be inside of the future
/// combinator's library.
///
/// There are two workarounds:
/// 1. Use the [`location!`] macro
/// 1. Use [`ResultExt`] instead
///
/// ```rust
/// # #[cfg(feature = "futures")] {
/// # use snafu::{prelude::*, Location, location};
/// // Non-ideal: will report where `wrapped_error_future` is `.await`ed.
/// # let error_future = async { AnotherSnafu.fail::<()>() };
/// let wrapped_error_future = error_future.context(ImplicitLocationSnafu);
///
/// // Better: will report the location of `.context`.
/// # let error_future = async { AnotherSnafu.fail::<()>() };
/// let wrapped_error_future = async { error_future.await.context(ImplicitLocationSnafu) };
///
/// // Better: Will report the location of `location!`
/// # let error_future = async { AnotherSnafu.fail::<()>() };
/// let wrapped_error_future = error_future.with_context(|_| ExplicitLocationSnafu {
/// location: location!(),
/// });
///
/// # #[derive(Debug, Snafu)] struct AnotherError;
/// #[derive(Debug, Snafu)]
/// struct ImplicitLocationError {
/// source: AnotherError,
/// location: Location,
/// }
///
/// #[derive(Debug, Snafu)]
/// struct ExplicitLocationError {
/// source: AnotherError,
/// #[snafu(implicit(false))]
/// location: Location,
/// }
/// # }
/// ```
#[derive(Copy, Clone)]
pub struct Location {
/// The file where the error was reported
pub file: &'static str,
/// The line where the error was reported
pub line: u32,
/// The column where the error was reported
pub column: u32,
// Use `#[non_exhaustive]` when we upgrade to Rust 1.40
_other: (),
}
impl Location {
/// Constructs a `Location` using the given information
pub fn new(file: &'static str, line: u32, column: u32) -> Self {
Self {
file,
line,
column,
_other: (),
}
}
}
#[cfg(feature = "rust_1_46")]
impl Default for Location {
#[track_caller]
fn default() -> Self {
let loc = core::panic::Location::caller();
Self {
file: loc.file(),
line: loc.line(),
column: loc.column(),
_other: (),
}
}
}
#[cfg(feature = "rust_1_46")]
impl GenerateImplicitData for Location {
#[inline]
#[track_caller]
fn generate() -> Self {
Self::default()
}
}
impl fmt::Debug for Location {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Location")
.field("file", &self.file)
.field("line", &self.line)
.field("column", &self.column)
.finish()
}
}
impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{file}:{line}:{column}",
file = self.file,
line = self.line,
column = self.column,
)
}
}
/// Constructs a [`Location`] using the current file, line, and column.
#[macro_export]
macro_rules! location {
() => {
Location::new(file!(), line!(), column!())
};
}
/// A basic error type that you can use as a first step to better
/// error handling.
///
/// You can use this type in your own application as a quick way to
/// create errors or add basic context to another error. This can also
/// be used in a library, but consider wrapping it in an
/// [opaque](guide::opaque) error to avoid putting the SNAFU crate in
/// your public API.
///
/// ## Examples
///
/// ```rust
/// use snafu::prelude::*;
///
/// type Result<T, E = snafu::Whatever> = std::result::Result<T, E>;
///
/// fn subtract_numbers(a: u32, b: u32) -> Result<u32> {
/// if a > b {
/// Ok(a - b)
/// } else {
/// whatever!("Can't subtract {} - {}", a, b)
/// }
/// }
///
/// fn complicated_math(a: u32, b: u32) -> Result<u32> {
/// let val = subtract_numbers(a, b).whatever_context("Can't do the math")?;
/// Ok(val * 2)
/// }
/// ```
///
/// See [`whatever!`][] for detailed usage instructions.
///
/// ## Limitations
///
/// When wrapping errors, only the backtrace from the shallowest
/// function is guaranteed to be available. If you need the deepest
/// possible trace, consider creating a custom error type and [using
/// `#[snafu(backtrace)]` on the `source`
/// field](Snafu#controlling-backtraces). If a best-effort attempt is
/// sufficient, see the [`backtrace`][Self::backtrace] method.
///
/// When the standard library stabilizes backtrace support, this
/// behavior may change.
#[derive(Debug, Snafu)]
#[snafu(crate_root(crate))]
#[snafu(whatever)]
#[snafu(display("{message}"))]
#[cfg(any(feature = "std", test))]
pub struct Whatever {
#[snafu(source(from(Box<dyn std::error::Error>, Some)))]
source: Option<Box<dyn std::error::Error>>,
message: String,
backtrace: Backtrace,
}
#[cfg(any(feature = "std", test))]
impl Whatever {
/// Gets the backtrace from the deepest `Whatever` error. If none
/// of the underlying errors are `Whatever`, returns the backtrace
/// from when this instance was created.
pub fn backtrace(&self) -> Option<&Backtrace> {
let mut best_backtrace = &self.backtrace;
let mut source = self.source();
while let Some(s) = source {
if let Some(this) = s.downcast_ref::<Self>() {
best_backtrace = &this.backtrace;
}
source = s.source();
}
Some(best_backtrace)
}
}