[][src]Trait evitable::OptionExt

pub trait OptionExt<T, C: ErrorContext> {
    fn context(self, f: impl FnOnce() -> C) -> Result<T, C::Error>;
}

Extension trait for option and result types for easy convertion to evitable errors.

Required methods

fn context(self, f: impl FnOnce() -> C) -> Result<T, C::Error>

Convert to a Result where ther error case is constructed from the given context factory.

Arguments

  • f - Error context factory

Example

 #[derive(ErrorContext)]
 #[evitable(description = "Error")]
 pub struct Context(u8);

 // Later
 let option_error: Option<u8> = None;
 let io_error: std::io::Result<u8> = Err(io::Error::from(io::ErrorKind::NotFound));
 let option_ok: Option<u8> = Some(42);
 let io_ok: std::io::Result<u8> = Ok(42);

 // The functions here are called
 let error_with_source = io_error.context(|| Context(42));
 let error_without_source = option_error.context(|| Context(42));

 // The functions here will never be called
 let ok_option = option_ok.context(|| Context(unimplemented!()));
 let ok_result = io_ok.context(|| Context(unimplemented!()));

 assert!(error_with_source.unwrap_err().source().is_some());
 assert!(error_without_source.unwrap_err().source().is_none());

 ok_option.unwrap();
 ok_result.unwrap();
Loading content...

Implementations on Foreign Types

impl<T, C: ErrorContext> OptionExt<T, C> for Option<T>[src]

impl<T, E: StdError + 'static, C: ErrorContext> OptionExt<T, C> for Result<T, E>[src]

Loading content...

Implementors

Loading content...