New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Easy way to turn Error::NotFound into an Option #1273

Closed
icefoxen opened this Issue Oct 24, 2017 · 2 comments

Comments

Projects
None yet
2 participants
@icefoxen

icefoxen commented Oct 24, 2017

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.

@sgrif

This comment has been minimized.

Member

sgrif commented Oct 27, 2017

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

@sgrif sgrif closed this Oct 27, 2017

@icefoxen

This comment has been minimized.

icefoxen commented Oct 29, 2017

My mistake for not seeing it then, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment