ResultExt

Trait ResultExt 

Source
pub trait ResultExt<T, E> {
    // Required methods
    fn ctx(self, build: impl FnOnce() -> Context) -> Result<T, Error>
       where E: CoreError + Send + Sync + 'static;
    fn context(self, msg: impl Into<Cow<'static, str>>) -> Result<T, Error>
       where E: CoreError + Send + Sync + 'static;
}
Expand description

Extension trait for enriching Result errors with Context.

The ctx method converts the error side of a Result into Error while attaching metadata, category and edit policy captured by Context.

§Examples

use std::io::{Error as IoError, ErrorKind};

use masterror::{AppErrorKind, Context, ResultExt, field};

fn validate() -> Result<(), IoError> {
    Err(IoError::from(ErrorKind::Other))
}

let err = validate()
    .ctx(|| Context::new(AppErrorKind::Validation).with(field::str("phase", "validate")))
    .unwrap_err();

assert_eq!(err.kind, AppErrorKind::Validation);
assert!(err.metadata().get("phase").is_some());

Required Methods§

Source

fn ctx(self, build: impl FnOnce() -> Context) -> Result<T, Error>
where E: CoreError + Send + Sync + 'static,

Convert an error into Error using Context supplied by build.

Source

fn context(self, msg: impl Into<Cow<'static, str>>) -> Result<T, Error>
where E: CoreError + Send + Sync + 'static,

Wrap the error with a simple context message.

This is a convenience method equivalent to anyhow’s .context(). For more control, use ctx.

§Examples
use std::io::{Error as IoError, ErrorKind};

use masterror::ResultExt;

fn read_config() -> Result<String, IoError> {
    Err(IoError::from(ErrorKind::NotFound))
}

let err = read_config()
    .context("Failed to read config file")
    .unwrap_err();

assert!(err.source_ref().is_some());

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T, E> ResultExt<T, E> for Result<T, E>

Source§

fn ctx(self, build: impl FnOnce() -> Context) -> Result<T, Error>
where E: CoreError + Send + Sync + 'static,

Source§

fn context(self, msg: impl Into<Cow<'static, str>>) -> Result<T, Error>
where E: CoreError + Send + Sync + 'static,

Implementors§