failure/macros.rs
1/// Exits a function early with an `Error`.
2///
3/// The `bail!` macro provides an easy way to exit a function. `bail!(X)` is
4/// equivalent to writing:
5///
6/// ```rust,ignore
7/// return Err(format_err!(X))
8/// ```
9#[macro_export]
10macro_rules! bail {
11 ($e:expr) => {
12 return Err($crate::err_msg($e));
13 };
14 ($fmt:expr, $($arg:tt)*) => {
15 return Err($crate::err_msg(format!($fmt, $($arg)*)));
16 };
17}
18
19/// Exits a function early with an `Error` if the condition is not satisfied.
20///
21/// Similar to `assert!`, `ensure!` takes a condition and exits the function
22/// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`,
23/// it does not panic.
24#[macro_export(local_inner_macros)]
25macro_rules! ensure {
26 ($cond:expr) => {
27 if !($cond) {
28 bail!("{}", _failure__stringify!($cond));
29 }
30 };
31 ($cond:expr, $e:expr) => {
32 if !($cond) {
33 bail!($e);
34 }
35 };
36 ($cond:expr, $fmt:expr, $($arg:tt)*) => {
37 if !($cond) {
38 bail!($fmt, $($arg)*);
39 }
40 };
41}
42
43#[doc(hidden)]
44#[macro_export]
45macro_rules! _failure__stringify {
46 ($($inner:tt)*) => {
47 stringify! { $($inner)* }
48 }
49}
50
51/// Constructs an `Error` using the standard string interpolation syntax.
52///
53/// ```rust
54/// #[macro_use] extern crate failure;
55///
56/// fn main() {
57/// let code = 101;
58/// let err = format_err!("Error code: {}", code);
59/// }
60/// ```
61#[macro_export]
62macro_rules! format_err {
63 ($($arg:tt)*) => { $crate::err_msg(format!($($arg)*)) }
64}