Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Show use of .fail() method in user guide #207

Open
tkaitchuck opened this issue Jan 20, 2020 · 3 comments
Open

Show use of .fail() method in user guide #207

tkaitchuck opened this issue Jan 20, 2020 · 3 comments

Comments

@tkaitchuck
Copy link

tkaitchuck commented Jan 20, 2020

I am not sure is this is a duplicate of #192
but I found myself in the following situation:

match type_of_thing {
  type1 => //do something
  type2 => //something else
  _ => ensure!(false, InvalidType { type: type_of_thing })
}

Of course this doesn't work if the match block is expected to return a result type.
I don't really see any neat way to do that if the InvalidType error is going to contain a backtrace.

So from my POV it would be ideal to have some other macro which works like ensure, but doesn't take the boolean.

@tkaitchuck tkaitchuck changed the title Unconditional version on ensure Unconditional version of ensure Jan 20, 2020
@shepmaster
Copy link
Owner

One thing mentioned in #192 is this:

ContextSelector {/* ... */}.fail();

Applied, it would look like

use snafu::{Backtrace, Snafu};

#[derive(Debug, Snafu)]
enum Error {
    InvalidType { v: i32, backtrace: Backtrace },
}

type Result<T, E = Error> = std::result::Result<T, E>;

fn example() -> Result<()> {
    let v = 42;

    match v {
        1 => println!("do something"),
        2 => println!("something else"),
        _ => InvalidType { v }.fail()?,
    };

    Ok(())
}

Does that work for your case?

@shepmaster
Copy link
Owner

Comparing the two possibilities shows it's only a single character difference:

InvalidType { v }.fail()?
bail!(InvalidType { v })

@tkaitchuck
Copy link
Author

tkaitchuck commented Jan 24, 2020

Awesome. That works. It just was not very discoverable. Perhaps an example showing that could be added to the docs.

@tkaitchuck tkaitchuck changed the title Unconditional version of ensure Show use of .fail() method in user guide May 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants