Better way to rap returning errors

Just asking for a quick code-review. This function works (and what it does isn't super important), but I feel like there is a better way to propagate the results rather than to just re-wrap them.

fn from_buffer(word_vector: &Vec<u8>) -> Result<u8, HeaderErrors> {
    match a_function_that_returns_a_result(word_vector) {
        // I shouldn't have to rewrap this, right?
        Ok(number_of_messages) => Ok(number_of_messages),

        // This is the only reason for the match statement.
        // I just want to pull the error value and put it inside my own enum
        Err(error) => Err(HeaderErrors::InvalidValue(error)),
    }
}

This is more for learning that anything. So, I'm not looking to use another crate or an error chain. Just "can I avoid this match and simply bubble up a REWRAPPED error variant if an error is encountered?"

Thanks in advance.

Implement From for YourError. Then you can use question mark operator.

P.S. Crate thiserror has a macro does exactly this.

The direct short replacement for your match is Result::map_err(), which applies a function to the Err variant's value and passes Ok through unchanged:

fn from_buffer(word_vector: &Vec<u8>) -> Result<u8, HeaderErrors> {
    a_function_that_returns_a_result(word_vector)
        .map_err(HeaderErrors::InvalidValue)
}

As mentioned in the previous post, implementing From for error wrappers is a good idea, but map_err() is there for you when the conversion is context-specific, or you don't want to expose it as an always-public trait implementation. If you do choose to implement From, then you would be able to use the ? operator's implicit conversion like:

fn from_buffer(word_vector: &Vec<u8>) -> Result<u8, HeaderErrors> {
    Ok(a_function_that_returns_a_result(word_vector)?)
}

It's a little awkward in this case since one of the purposes of ? is unwrapping the Result, but when your function only does one thing like this, you have to rewrap the result. In more complex functions, ? makes more sense.

6 Likes