Skip to content
This repository was archived by the owner on Aug 16, 2021. It is now read-only.

Commit c262167

Browse files
aldanorYamakaky
authored andcommitted
Add ensure! convenience macro (#135)
1 parent 27c6833 commit c262167

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Unreleased
22

33
- [Add a new constructor for `Error`: `with_chain`.](https://github.com/brson/error-chain/pull/126)
4+
- [Add the `ensure!` macro.](https://github.com/brson/error-chain/pull/135)
45

56
# 0.9.0
67

src/lib.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,42 @@ macro_rules! bail {
617617
};
618618
}
619619

620+
/// Exits a function early with an error if the condition is not satisfied
621+
///
622+
/// The `ensure!` macro is a convenience helper that provides a way to exit
623+
/// a function with an error if the given condition fails.
624+
///
625+
/// As an example, `ensure!(condition, "error code: {}", errcode)` is equivalent to
626+
///
627+
/// ```
628+
/// # #[macro_use] extern crate error_chain;
629+
/// # error_chain! { }
630+
/// # fn main() { }
631+
/// # fn foo() -> Result<()> {
632+
/// # let errcode = 0u8;
633+
/// # let condition = true;
634+
/// if !condition {
635+
/// bail!("error code: {}", errcode);
636+
/// }
637+
/// # Ok(())
638+
/// # }
639+
/// ```
640+
///
641+
/// See documentation for `bail!` macro for further details.
642+
#[macro_export]
643+
macro_rules! ensure {
644+
($cond:expr, $e:expr) => {
645+
if !($cond) {
646+
bail!($e);
647+
}
648+
};
649+
($cond:expr, $fmt:expr, $($arg:tt)+) => {
650+
if !($cond) {
651+
bail!($fmt, $($arg)+);
652+
}
653+
};
654+
}
655+
620656
#[doc(hidden)]
621657
pub mod mock {
622658
error_chain!{}

tests/tests.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,21 @@ fn bail() {
524524
}
525525
}
526526

527+
#[test]
528+
fn ensure() {
529+
error_chain! {
530+
errors { Bar }
531+
}
532+
533+
fn foo(x: u8) -> Result<()> {
534+
ensure!(x == 42, ErrorKind::Bar);
535+
Ok(())
536+
}
537+
538+
assert!(foo(42).is_ok());
539+
assert!(foo(0).is_err());
540+
}
541+
527542
/// Since the `types` declaration is a list of symbols, check if we
528543
/// don't change their meaning or order.
529544
#[test]

0 commit comments

Comments
 (0)