]> git.proxmox.com Git - cargo.git/blob - vendor/failure/src/macros.rs
New upstream version 0.33.0
[cargo.git] / vendor / failure / src / 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]
10 macro_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)]
25 macro_rules! ensure {
26 ($cond:expr, $e:expr) => {
27 if !($cond) {
28 bail!($e);
29 }
30 };
31 ($cond:expr, $fmt:expr, $($arg:tt)*) => {
32 if !($cond) {
33 bail!($fmt, $($arg)*);
34 }
35 };
36 }
37
38 /// Constructs an `Error` using the standard string interpolation syntax.
39 ///
40 /// ```rust
41 /// #[macro_use] extern crate failure;
42 ///
43 /// fn main() {
44 /// let code = 101;
45 /// let err = format_err!("Error code: {}", code);
46 /// }
47 /// ```
48 #[macro_export]
49 macro_rules! format_err {
50 ($($arg:tt)*) => { $crate::err_msg(format!($($arg)*)) }
51 }