I'm trying to make a function that takes a Result and a bool and returns
> when the Result is Ok(value)
return Ok(value)
> when the Result is Err(_)
and the bool is true
return Ok(None)
> when the Result is Err(error)
and the bool is false
return Err(error.context("..."))
(.context()
is from anyhow
).
Unfortunately I'm getting a bit tangled up in Error and Result types.
use anyhow::{anyhow, Result};
use std::fs::File;
fn convert<T, E: std::error::Error + anyhow::Context<T, E>>(
result: std::result::Result<T, E>,
should_retry: bool,
) -> Result<Option<T>> {
Ok(match result {
Ok(v) => Some(v),
Err(err) => match should_retry {
false => { err.context("Retries exceeded")?; },
true => None,
},
})
}
fn always_fails() -> Result<()> {
Err(anyhow!("something happened"))
}
fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
let result = File::open("doesnt exist");
let file = match convert(result, false)? {
Some(f) => f,
None => { return Ok(()); },
};
let result = always_fails();
match convert(result, false)? {
Some(_) => {},
None => {},
};
Ok(())
}