Skip to content

Commit

Permalink
Merge pull request #183 from JasperDeSutter/patch-1
Browse files Browse the repository at this point in the history
Make ensure! macro work with opaque error types
  • Loading branch information
shepmaster authored Oct 8, 2019
2 parents afdb0f5 + c7aca46 commit 698aeed
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ use std::error;
macro_rules! ensure {
($predicate:expr, $context_selector:expr) => {
if !$predicate {
return $context_selector.fail();
return $context_selector.fail().map_err(core::convert::Into::into);
}
};
}
Expand Down
28 changes: 27 additions & 1 deletion tests/opaque.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
mod inner {
use snafu::Snafu;
use snafu::{ensure, Snafu};

#[derive(Debug, Snafu)]
pub struct Error(InnerError);
Expand All @@ -8,6 +8,16 @@ mod inner {
Ok(a()? + b()?)
}

pub fn not_positive(value: i32) -> Result<i32, Error> {
ensure!(value < 1, TooBig { count: value });
Ok(value)
}

pub fn boxed_inner(value: i32) -> Result<i32, Box<dyn std::error::Error>> {
ensure!(value < 1, TooBig { count: value });
Ok(value)
}

#[derive(Debug, Snafu)]
enum InnerError {
#[snafu(display = r#"("The value {} is too big", count)"#)]
Expand All @@ -30,3 +40,19 @@ fn implements_error() {
let e = inner::api().unwrap_err();
assert!(e.to_string().contains("too big"));
}

#[test]
fn ensure_opaque() {
assert!(inner::not_positive(-1).is_ok());

let e = inner::not_positive(2).unwrap_err();
assert!(e.to_string().contains("too big"));
}

#[test]
fn ensure_boxed() {
assert!(inner::boxed_inner(-1).is_ok());

let e = inner::boxed_inner(2).unwrap_err();
assert!(e.to_string().contains("too big"));
}

0 comments on commit 698aeed

Please sign in to comment.