I'm trying to be a grown up about how I handle errors in my rust code, and not just unwrap
everything. I'm currently using Miette.
I want to be able to use the ?;
syntax, preferably in a very lightweight way. I'm running into problems with what seems like it should be a very easy and common case - converting an Option into a Result.
pub fn foo() -> miette::Result<String>{
let result = bar().some_function("Bar gave us nothing")?;
Ok(result)
}
fn bar () -> Option<String>{
Some("bar".to_string())
}
I've tried a bunch of options to make some_function
work, but they all end up messy. The best I've managed to do so far is:
pub fn foo() -> miette::Result<String>{
let result = match bar(){
Some(s) => Ok::<String, miette::Report>(s),
None => miette::bail!("No bar")
}?;
Ok(result)
}
fn bar () -> Option<String>{
Some("bar".to_string())
}
That seems to work but it'd be a pain to use everywhere... I could wrap it into a custom function and even make some trait in my project implemented on Option<T>
, but I feel like I'm missing something obvious. What's the idiomatic way to approach this?
EDIT:
After some fiddling, I found that
let result = bar().ok_or(miette::Error::msg("Bar Failed"))?;
works. That's vaguely acceptable but I'd still like to clean it up more, ideally down to a single call... is there a better way?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744241959a4564748.html
评论列表(0条)