Trait snafu::OptionExt[][src]

pub trait OptionExt<T>: Sized {
    fn context<C, E>(self, context: C) -> Result<T, E>
    where
        C: IntoError<E, Source = NoneError>,
        E: Error + ErrorCompat
;
fn with_context<F, C, E>(self, context: F) -> Result<T, E>
    where
        F: FnOnce() -> C,
        C: IntoError<E, Source = NoneError>,
        E: Error + ErrorCompat
; }
Expand description

Additions to Option.

Required methods

Convert an Option into a Result with additional context-sensitive information.

use snafu::{OptionExt, Snafu};

#[derive(Debug, Snafu)]
enum Error {
    UserLookup { user_id: i32 },
}

fn example(user_id: i32) -> Result<(), Error> {
    let name = username(user_id).context(UserLookup { user_id })?;
    println!("Username was {}", name);
    Ok(())
}

fn username(user_id: i32) -> Option<String> {
    /* ... */
}

Note that the context selector will call Into::into on each field, so the types are not required to exactly match.

Convert an Option into a Result with lazily-generated context-sensitive information.

use snafu::{OptionExt, Snafu};

#[derive(Debug, Snafu)]
enum Error {
    UserLookup {
        user_id: i32,
        previous_ids: Vec<i32>,
    },
}

fn example(user_id: i32) -> Result<(), Error> {
    let name = username(user_id).with_context(|| UserLookup {
        user_id,
        previous_ids: Vec::new(),
    })?;
    println!("Username was {}", name);
    Ok(())
}

fn username(user_id: i32) -> Option<String> {
    /* ... */
}

Note that this may not be needed in many cases because the context selector will call Into::into on each field.

Implementations on Foreign Types

Implementors