Concrete Error type for general "not found"

Hi,

I have a HashMap and when searching a key that is not in it, I wanted to return an error (std Error trait). What existing concrete error type do most people use for such case? (I felt io::Error is not best suited here).

code is like this:

pub fn find_record(&self, user_id: &str) -> Result<UserRecord, Box<dyn Error>> {
    if !self.user_map.contains_key(user_id) {
        Err(<?what_error_type_for_not_found?>)
    }
    <snip>
}

Thanks.

Typically, I'd return -> Result<Option<UserRecord>, ErrorType>.

That way, callers can easily use ? to handle fatal errors like "couldn't connect to the database", and can choose to gracefully handle "that user doesn't exist".

If your method can't fail for any reason other than "not found", I'd suggest -> Option<UserRecord>.

Also see http://sled.rs/errors

In my case, the actual business logic is more complex and requires that "not found" is treated as an error, and there are more conditions in the function as well. Hence I don't want to use Option as it implies it's okay to have None value.

For now, I just defined my own type that implements Error trait so I can move on. But I'm surprised that by default Rust does not have much common error types (my understanding is that here is all: https://doc.rust-lang.org/std/error/trait.Error.html#implementors ) .

If you want a custom error for NotFound, I'd suggest thiserror.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.