#error #error-handling #result #derive-error #debugging #map-err #error-conversion

and_then_map_err

Provides traits for chaining Result operations with different error types WITHOUT the need for intermediate map_err calls

1 stable release

1.0.0 Aug 7, 2024

#27 in #derive-error

MIT license

10KB

and-then-map-err

Provides traits for chaining Result operations with different error types WITHOUT the need for intermediate map_err calls.


lib.rs:

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()))));

No runtime deps