0

I have a function that shouldn't return a result, but can possibly return an error, so I have the return type as Result<(), Box<dyn error::Error>>. The functions my function calls have return types like Result<T, Err1> and Option<V>. I want to minimize the amount of lines dealing with error handling. Here is an example of how I'm currently doing this:

match match some_function_returning_an_Option() {
    Some(x) => x,
    None => return Err(MyError.into()),
}
.some_function_a()
.some_function_returning_a_Result()
{
    Ok(x) => x,
    Err(e) => return Err(e.into()),
}
.some_function_b()

I'm new to Rust and I'm wondering if there is a more idiomatic way of doing this.

Johan
  • 110
  • 1
  • 6
  • You should call this on your `Option` to convert it to `Result` : https://doc.rust-lang.org/std/option/enum.Option.html#method.ok_or_else – Angelicos Phosphoros Mar 26 '21 at 21:40
  • 1
    are you aware of the [`?` operator](https://doc.rust-lang.org/edition-guide/rust-2018/error-handling-and-panics/the-question-mark-operator-for-easier-error-handling.html)? – kmdreko Mar 26 '21 at 21:42
  • @AngelicosPhosphoros The problem with ok_or_else in my case is that the T of my Result is (), while the functions I'm calling have arbitrary non-() types. – Johan Mar 26 '21 at 21:46
  • You could call `map` method and replace any value by `()`. – Angelicos Phosphoros Mar 26 '21 at 21:51
  • 1
    tl;dr: `some_function_returning_an_Option().ok_or(MyError)?.some_function_a().some_function_returning_a_Result()?.some_function_b()` – trent Mar 26 '21 at 22:14
  • If the above doesn't work for you, please provide a [mre]. – trent Mar 26 '21 at 22:17

0 Answers0