]> git.proxmox.com Git - rustc.git/blob - vendor/anyhow/src/macros.rs
New upstream version 1.49.0~beta.4+dfsg1
[rustc.git] / vendor / anyhow / src / macros.rs
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, $msg:literal $(,)?) => {
117 if !$cond {
118 return $crate::private::Err($crate::anyhow!($msg));
119 }
120 };
121 ($cond:expr, $err:expr $(,)?) => {
122 if !$cond {
123 return $crate::private::Err($crate::anyhow!($err));
124 }
125 };
126 ($cond:expr, $fmt:expr, $($arg:tt)*) => {
127 if !$cond {
128 return $crate::private::Err($crate::anyhow!($fmt, $($arg)*));
129 }
130 };
131 }
132
133 /// Construct an ad-hoc error from a string or existing non-`anyhow` error
134 /// value.
135 ///
136 /// This evaluates to an [`Error`][crate::Error]. It can take either just a
137 /// string, or a format string with arguments. It also can take any custom type
138 /// which implements `Debug` and `Display`.
139 ///
140 /// If called with a single argument whose type implements `std::error::Error`
141 /// (in addition to `Debug` and `Display`, which are always required), then that
142 /// Error impl's `source` is preserved as the `source` of the resulting
143 /// `anyhow::Error`.
144 ///
145 /// # Example
146 ///
147 /// ```
148 /// # type V = ();
149 /// #
150 /// use anyhow::{anyhow, Result};
151 ///
152 /// fn lookup(key: &str) -> Result<V> {
153 /// if key.len() != 16 {
154 /// return Err(anyhow!("key length must be 16 characters, got {:?}", key));
155 /// }
156 ///
157 /// // ...
158 /// # Ok(())
159 /// }
160 /// ```
161 #[macro_export]
162 macro_rules! anyhow {
163 ($msg:literal $(,)?) => {
164 // Handle $:literal as a special case to make cargo-expanded code more
165 // concise in the common case.
166 $crate::private::new_adhoc($msg)
167 };
168 ($err:expr $(,)?) => ({
169 use $crate::private::kind::*;
170 let error = $err;
171 (&error).anyhow_kind().new(error)
172 });
173 ($fmt:expr, $($arg:tt)*) => {
174 $crate::private::new_adhoc(format!($fmt, $($arg)*))
175 };
176 }