Trait astral::error::ResultExt

pub trait ResultExt<T, E> {
    fn context<Kind>(self, kind: Kind) -> Result<T, Error<Kind>>;
    fn chain<Kind, Source>(
        self,
        kind: Kind,
        source: Source
    ) -> Result<T, Error<Kind>>
    where
        Source: Into<Box<dyn Error + Send + Sync + 'static, Global>>
; fn chain_with<Kind, Source, F>(
        self,
        kind: Kind,
        source: F
    ) -> Result<T, Error<Kind>>
    where
        Source: Into<Box<dyn Error + Send + Sync + 'static, Global>>,
        F: FnOnce() -> Source
; }
Expand description

Extension methods for Result.

Required Methods

Associates the error with an error kind.

Example
use std::{error, fmt};

use astral::error::ResultExt;

#[derive(Debug)]
struct CustomError;

impl fmt::Display for CustomError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl error::Error for CustomError {}

#[derive(Debug, PartialEq)]
enum MyErrorKind {
    Variant,
}

let x = (|| -> Result<(), CustomError> {
    Err(CustomError)?
})().context(MyErrorKind::Variant).unwrap_err();

assert_eq!(x.kind(), &MyErrorKind::Variant);

Creates a new Error, associates it with an error kind and sets the old error as source.

Example
use std::{error, fmt};

use astral::error::ResultExt;

#[derive(Debug)]
struct CustomError;

impl fmt::Display for CustomError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl error::Error for CustomError {}

#[derive(Debug)]
enum MyErrorKind {
    Variant,
}

impl fmt::Display for MyErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

let x = (|| -> Result<(), CustomError> {
    Err(CustomError)?
})().chain(MyErrorKind::Variant, "An error occured").unwrap_err();

assert_eq!(x.to_string(), "An error occured");

Creates a new Error, associates it with an error kind and sets the old error as source by applying the provided closure FnOnce() -> impl Into<Box<dyn error::Error + Send + Sync>>.

Example
use std::{error, fmt};

use astral::error::ResultExt;

#[derive(Debug)]
struct CustomError;

impl fmt::Display for CustomError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl error::Error for CustomError {}

#[derive(Debug)]
enum MyErrorKind {
    Variant,
}

impl fmt::Display for MyErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

let x = (|| -> Result<(), CustomError> {
    Err(CustomError)?
})().chain_with(MyErrorKind::Variant, || "An error occured").unwrap_err();

assert_eq!(x.to_string(), "An error occured");

Implementations on Foreign Types

Implementors