Crate and_then_map_err

Source
Expand description

§and_then_map_err

and_then_map_err provides traits for chaining Result operations with different error types without needing intermediate map_err calls. This allows more flexible error handling by converting error types between chained operations.

§Features

  • AndThenMapErr trait: Enables chaining Result operations where the error type can be converted.
  • MapErrAndThen trait: Enables mapping the error type of initial Result before chaining another operation.

§Examples

use thiserror::Error;
use and_then_map_err::{AndThenMapErr, MapErrAndThen};

#[derive(Error, Debug, Eq, PartialEq)]
pub enum ParentError {
    #[error("parent error: {0}")]
    Parent(String),
    #[error("parent error from child error: {0}")]
    FromChild(#[from] ChildError),
}

#[derive(Error, Debug, Eq, PartialEq)]
pub enum ChildError {
    #[error("child error: {0}")]
    Child(String),
}

let result_or_parent_err: Result<(), ParentError> = Ok(());
let new_result_or_parent_err: Result<(), ParentError> = result_or_parent_err.and_then_map_err(|x| {
    Err(ChildError::Child("error occurred afterwards".to_string()))
});
assert_eq!(new_result_or_parent_err, Err(ParentError::FromChild(ChildError::Child("error occurred afterwards".to_string()))));

let result_or_child_err: Result<(), ChildError> = Err(ChildError::Child("initial error".to_string()));
let new_result_or_parent_err: Result<(), ParentError> = result_or_child_err.map_err_and_then(|x| {
    Ok(x)
});
assert_eq!(new_result_or_parent_err, Err(ParentError::FromChild(ChildError::Child("initial error".to_string()))));

Traits§

AndThenMapErr
The and_then_map_err trait allows for error mapping on Result types. This trait converts an error in the result of the operation Result<U, E2> to a different error type E1 if the initial operation fails.
MapErrAndThen
The map_err_and_then trait allows for error mapping on Result types. This trait converts an error in the initial Result<T, E1> to a different error type E2 if the operation fails.