1 /// Return early with an error.
2 ///
3 /// This macro is equivalent to `return Err(`[`anyhow!($args...)`][anyhow!]`)`.
4 ///
5 /// The surrounding function's or closure's return value is required to be
6 /// `Result<_,`[`anyhow::Error`][crate::Error]`>`.
7 ///
8 /// # Example
9 ///
10 /// ```
11 /// # use anyhow::{bail, Result};
12 /// #
13 /// # fn has_permission(user: usize, resource: usize) -> bool {
14 /// #     true
15 /// # }
16 /// #
17 /// # fn main() -> Result<()> {
18 /// #     let user = 0;
19 /// #     let resource = 0;
20 /// #
21 /// if !has_permission(user, resource) {
22 ///     bail!("permission denied for accessing {}", resource);
23 /// }
24 /// #     Ok(())
25 /// # }
26 /// ```
27 ///
28 /// ```
29 /// # use anyhow::{bail, Result};
30 /// # use thiserror::Error;
31 /// #
32 /// # const MAX_DEPTH: usize = 1;
33 /// #
34 /// #[derive(Error, Debug)]
35 /// enum ScienceError {
36 ///     #[error("recursion limit exceeded")]
37 ///     RecursionLimitExceeded,
38 ///     # #[error("...")]
39 ///     # More = (stringify! {
40 ///     ...
41 ///     # }, 1).1,
42 /// }
43 ///
44 /// # fn main() -> Result<()> {
45 /// #     let depth = 0;
46 /// #
47 /// if depth > MAX_DEPTH {
48 ///     bail!(ScienceError::RecursionLimitExceeded);
49 /// }
50 /// #     Ok(())
51 /// # }
52 /// ```
53 #[macro_export]
54 macro_rules! bail {
55     ($msg:literal $(,)?) => {
56         return $crate::private::Err($crate::anyhow!($msg))
57     };
58     ($err:expr $(,)?) => {
59         return $crate::private::Err($crate::anyhow!($err))
60     };
61     ($fmt:expr, $($arg:tt)*) => {
62         return $crate::private::Err($crate::anyhow!($fmt, $($arg)*))
63     };
64 }
65 
66 /// Return early with an error if a condition is not satisfied.
67 ///
68 /// This macro is equivalent to `if !$cond { return
69 /// Err(`[`anyhow!($args...)`][anyhow!]`); }`.
70 ///
71 /// The surrounding function's or closure's return value is required to be
72 /// `Result<_,`[`anyhow::Error`][crate::Error]`>`.
73 ///
74 /// Analogously to `assert!`, `ensure!` takes a condition and exits the function
75 /// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`
76 /// rather than panicking.
77 ///
78 /// # Example
79 ///
80 /// ```
81 /// # use anyhow::{ensure, Result};
82 /// #
83 /// # fn main() -> Result<()> {
84 /// #     let user = 0;
85 /// #
86 /// ensure!(user == 0, "only user 0 is allowed");
87 /// #     Ok(())
88 /// # }
89 /// ```
90 ///
91 /// ```
92 /// # use anyhow::{ensure, Result};
93 /// # use thiserror::Error;
94 /// #
95 /// # const MAX_DEPTH: usize = 1;
96 /// #
97 /// #[derive(Error, Debug)]
98 /// enum ScienceError {
99 ///     #[error("recursion limit exceeded")]
100 ///     RecursionLimitExceeded,
101 ///     # #[error("...")]
102 ///     # More = (stringify! {
103 ///     ...
104 ///     # }, 1).1,
105 /// }
106 ///
107 /// # fn main() -> Result<()> {
108 /// #     let depth = 0;
109 /// #
110 /// ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);
111 /// #     Ok(())
112 /// # }
113 /// ```
114 #[macro_export]
115 macro_rules! ensure {
116     ($cond:expr $(,)?) => {
117         $crate::ensure!(
118             $cond,
119             $crate::private::concat!("Condition failed: `", $crate::private::stringify!($cond), "`"),
120         )
121     };
122     ($cond:expr, $msg:literal $(,)?) => {
123         if !$cond {
124             return $crate::private::Err($crate::anyhow!($msg));
125         }
126     };
127     ($cond:expr, $err:expr $(,)?) => {
128         if !$cond {
129             return $crate::private::Err($crate::anyhow!($err));
130         }
131     };
132     ($cond:expr, $fmt:expr, $($arg:tt)*) => {
133         if !$cond {
134             return $crate::private::Err($crate::anyhow!($fmt, $($arg)*));
135         }
136     };
137 }
138 
139 /// Construct an ad-hoc error from a string or existing non-`anyhow` error
140 /// value.
141 ///
142 /// This evaluates to an [`Error`][crate::Error]. It can take either just a
143 /// string, or a format string with arguments. It also can take any custom type
144 /// which implements `Debug` and `Display`.
145 ///
146 /// If called with a single argument whose type implements `std::error::Error`
147 /// (in addition to `Debug` and `Display`, which are always required), then that
148 /// Error impl's `source` is preserved as the `source` of the resulting
149 /// `anyhow::Error`.
150 ///
151 /// # Example
152 ///
153 /// ```
154 /// # type V = ();
155 /// #
156 /// use anyhow::{anyhow, Result};
157 ///
158 /// fn lookup(key: &str) -> Result<V> {
159 ///     if key.len() != 16 {
160 ///         return Err(anyhow!("key length must be 16 characters, got {:?}", key));
161 ///     }
162 ///
163 ///     // ...
164 ///     # Ok(())
165 /// }
166 /// ```
167 #[macro_export]
168 macro_rules! anyhow {
169     ($msg:literal $(,)?) => {
170         // Handle $:literal as a special case to make cargo-expanded code more
171         // concise in the common case.
172         $crate::private::new_adhoc($msg)
173     };
174     ($err:expr $(,)?) => ({
175         use $crate::private::kind::*;
176         match $err {
177             error => (&error).anyhow_kind().new(error),
178         }
179     });
180     ($fmt:expr, $($arg:tt)*) => {
181         $crate::private::new_adhoc(format!($fmt, $($arg)*))
182     };
183 }
184