Trait snafu::OptionExt

source ·
pub trait OptionExt<T>: Sized {
    // Required methods
    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§

source

fn context<C, E>(self, context: C) -> Result<T, E>
where C: IntoError<E, Source = NoneError>, E: Error + ErrorCompat,

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.

source

fn with_context<F, C, E>(self, context: F) -> Result<T, E>
where F: FnOnce() -> C, C: IntoError<E, Source = NoneError>, E: Error + ErrorCompat,

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.

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl<T> OptionExt<T> for Option<T>

source§

fn context<C, E>(self, context: C) -> Result<T, E>
where C: IntoError<E, Source = NoneError>, E: Error + ErrorCompat,

source§

fn with_context<F, C, E>(self, context: F) -> Result<T, E>
where F: FnOnce() -> C, C: IntoError<E, Source = NoneError>, E: Error + ErrorCompat,

Implementors§