Trait ResultExt

Source
pub trait ResultExt<T, E> {
    // Required methods
    fn compat(self) -> Result<T, Compat<E>>;
    fn context<D>(self, context: D) -> Result<T, Context<D>>
       where D: Display + Send + Sync + 'static;
    fn with_context<F, D>(self, f: F) -> Result<T, Context<D>>
       where F: FnOnce(&E) -> D,
             D: Display + Send + Sync + 'static;
}
Expand description

Extension methods for Result.

Required Methods§

Source

fn compat(self) -> Result<T, Compat<E>>

Wraps the error in Compat to make it compatible with older error handling APIs that expect std::error::Error.

§Examples
use std::error::Error;
struct CustomError;

impl Error for CustomError {
    fn description(&self) -> &str {
        "My custom error message"
    }

    fn cause(&self) -> Option<&Error> {
        None
    }
}

let x = (|| -> Result<(), failure::Error> {
    Err(CustomError).compat()?
})().with_context(|e| {
    format!("An error occured: {}", e)
}).unwrap_err();

let x = format!("{}", x);

assert_eq!(x, "An error occured: My custom error message");
Source

fn context<D>(self, context: D) -> Result<T, Context<D>>
where D: Display + Send + Sync + 'static,

Wraps the error type in a context type.

§Examples
#[derive(Fail, Debug)]
#[fail(display = "")]
struct CustomError;
  
let x = (|| -> Result<(), failure::Error> {
    Err(CustomError)?
})().context(format!("An error occured")).unwrap_err();

let x = format!("{}", x);

assert_eq!(x, "An error occured");
Source

fn with_context<F, D>(self, f: F) -> Result<T, Context<D>>
where F: FnOnce(&E) -> D, D: Display + Send + Sync + 'static,

Wraps the error type in a context type generated by looking at the error value.

§Examples
#[derive(Fail, Debug)]
#[fail(display = "My custom error message")]
struct CustomError;

let x = (|| -> Result<(), failure::Error> {
    Err(CustomError)?
})().with_context(|e| {
    format!("An error occured: {}", e)
}).unwrap_err();

let x = format!("{}", x);

assert_eq!(x, "An error occured: My custom error message");

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> ResultExt<T, Error> for Result<T, Error>

Source§

fn compat(self) -> Result<T, Compat<Error>>

Source§

fn context<D>(self, context: D) -> Result<T, Context<D>>
where D: Display + Send + Sync + 'static,

Source§

fn with_context<F, D>(self, f: F) -> Result<T, Context<D>>
where F: FnOnce(&Error) -> D, D: Display + Send + Sync + 'static,

Source§

impl<T, E> ResultExt<T, E> for Result<T, E>
where E: Fail,

Source§

fn compat(self) -> Result<T, Compat<E>>

Source§

fn context<D>(self, context: D) -> Result<T, Context<D>>
where D: Display + Send + Sync + 'static,

Source§

fn with_context<F, D>(self, f: F) -> Result<T, Context<D>>
where F: FnOnce(&E) -> D, D: Display + Send + Sync + 'static,

Implementors§