Skip to content

Commit 68b86f2

Browse files
authored
feat(error): add shared bail! and ensure! macros (#1263)
1 parent 2e2b5ed commit 68b86f2

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

  • crates/ironrdp-error/src

crates/ironrdp-error/src/lib.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,3 +200,59 @@ where
200200
Ok(())
201201
}
202202
}
203+
204+
/// Returns from the enclosing function with an [`Error`] built from a kind variant.
205+
///
206+
/// Three forms are supported:
207+
///
208+
/// - `bail!(kind)` — empty context.
209+
/// - `bail!(context, kind)` — explicit `&'static str` context.
210+
/// - `bail!(context, kind, source: source)` — explicit context plus a chained source error.
211+
///
212+
/// The kind type is inferred from the enclosing function's return type, which must be
213+
/// `Result<_, Error<Kind>>` (or any type alias resolving to it).
214+
///
215+
/// Mirrors the call-site shape of [`anyhow::bail!`] but produces a typed
216+
/// `Error<Kind>` rather than a type-erased `anyhow::Error`.
217+
///
218+
/// [`anyhow::bail!`]: https://docs.rs/anyhow/latest/anyhow/macro.bail.html
219+
#[macro_export]
220+
macro_rules! bail {
221+
($kind:expr $(,)?) => {
222+
return ::core::result::Result::Err($crate::Error::new("", $kind))
223+
};
224+
($context:expr, $kind:expr $(,)?) => {
225+
return ::core::result::Result::Err($crate::Error::new($context, $kind))
226+
};
227+
($context:expr, $kind:expr, source: $source:expr $(,)?) => {
228+
return ::core::result::Result::Err($crate::Error::new($context, $kind).with_source($source))
229+
};
230+
}
231+
232+
/// Returns from the enclosing function with an [`Error`] if the given condition is false.
233+
///
234+
/// Two forms are supported:
235+
///
236+
/// - `ensure!(condition, kind)` — empty context.
237+
/// - `ensure!(condition, context, kind)` — explicit `&'static str` context.
238+
///
239+
/// The kind type is inferred from the enclosing function's return type, which must be
240+
/// `Result<_, Error<Kind>>` (or any type alias resolving to it).
241+
///
242+
/// Mirrors the call-site shape of [`anyhow::ensure!`] but produces a typed
243+
/// `Error<Kind>` rather than a type-erased `anyhow::Error`.
244+
///
245+
/// [`anyhow::ensure!`]: https://docs.rs/anyhow/latest/anyhow/macro.ensure.html
246+
#[macro_export]
247+
macro_rules! ensure {
248+
($condition:expr, $kind:expr $(,)?) => {
249+
if !($condition) {
250+
return ::core::result::Result::Err($crate::Error::new("", $kind));
251+
}
252+
};
253+
($condition:expr, $context:expr, $kind:expr $(,)?) => {
254+
if !($condition) {
255+
return ::core::result::Result::Err($crate::Error::new($context, $kind));
256+
}
257+
};
258+
}

0 commit comments

Comments
 (0)