Diesel: Easy way to turn Error::NotFound into an Option

Created on 24 Oct 2017  路  2Comments  路  Source: diesel-rs/diesel

Wishlist item.

In my Rust code I very often find myself doing:

fn get_thing() -> Result<Option<Thing>> {
    let res = thing.filter(something)
        .select(stuff)
        .load::<Thing>(connection)?;
    match res {
       Ok(thing) => Ok(Some(thing)),
       Err(diesel::result::Error::NotFound) => Ok(None),
       Err(e) => Err(e)
}

This tends to happen when the absence of a Thing is perfectly valid, and we should just, say, create a new Thing from defaults, or do nothing, or even just report a different sort of error (which might be recoverable) than, say, a DatabaseError or DeserializationError (which probably isn't).

Is this common enough for anyone else that it's worth making a shortcut combinator? I'll happily make a PR for it.

Most helpful comment

You can call .optional(). We call this out in the documentation of every method that can return NotFound (which is basically just .get_result and .first

All 2 comments

You can call .optional(). We call this out in the documentation of every method that can return NotFound (which is basically just .get_result and .first

My mistake for not seeing it then, thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

astraw picture astraw  路  4Comments

sgrif picture sgrif  路  4Comments

jimmycuadra picture jimmycuadra  路  4Comments

kollapsderwellenfunktion picture kollapsderwellenfunktion  路  4Comments

kanekv picture kanekv  路  3Comments