Returning custom error from Vec binary search

How do I return a custom error from Vec binary search when the item is not present?

let who = ["account 1", "account 2", "account 3", "account 4", "account 5", "account 6"];
let insert = who.binary_search(&who).err().ok_or(Error::<T>::AlreadyVetoed)?;

error message

 cannot use the `?` operator in a method that returns `()`

You can't return an error in a function that doesn't have a Result as its return value.

It was done here

The function you've linked to returns DispatchResult, which is defined here as std::result::Result<(), DispatchError>.

1 Like

Slice's binary search returns a Result<usize, usize> with the error being where in the slice a new entry might fit. So wouldn't it be possible to use Result::map_err to transform it into your desired custom error?

1 Like

Are you sure it's the right code? The error message you've quoted doesn't seem to apply to the code you've linked to.

Check if you don't have the code inside a closure. That's a common source of this error, e.g.:

fn fallible(…) -> Result<…> {|x| bar(x)?);

won't work, even if foo is in a function returning result, because the bar call is in a closure that has its own return type.