pub trait WithError<E>: HKT {
type Success;
type ErrorOutput<G>;
// Required methods
fn fmap_error<F, G>(self, f: F) -> Self::ErrorOutput<G>
where F: Fn(E) -> G,
G: Clone;
fn to_result(self) -> Result<Self::Success, E>;
}
Expand description
Error handling trait for types that can fail with a specific error type.
This trait provides a common interface for working with different error handling
types such as Result
, Either
, and Validated
. It defines methods for
transforming errors and converting to standard Rust Result
types.
§Type Parameters
E
: The error type that can occur in the fallible computation
§Examples
Using WithError
with Result
:
use rustica::utils::error_utils::WithError;
use std::io;
// Define a function that works with any type implementing WithError
fn log_and_transform_error<T, E>(value: T) -> T::ErrorOutput<String>
where
T: WithError<E>,
E: std::fmt::Display + Clone,
{
value.fmap_error(|e| format!("Error occurred: {}", e))
}
// Use with a Result
let result: Result<i32, String> = Err("file not found".to_string());
let transformed = log_and_transform_error(result);
assert!(transformed.is_err());
Required Associated Types§
Sourcetype ErrorOutput<G>
type ErrorOutput<G>
The output type when mapping the error to a new type
Required Methods§
Sourcefn fmap_error<F, G>(self, f: F) -> Self::ErrorOutput<G>
fn fmap_error<F, G>(self, f: F) -> Self::ErrorOutput<G>
Maps a function over the error, transforming the error type.
This is similar to map_err
for Result
, but generalized to work with
any error handling type.
§Type Parameters
F
: Function type that transforms errorE
to errorG
G
: The new error type after transformation
§Examples
use rustica::utils::error_utils::WithError;
let result: Result<i32, &str> = Err("not found");
let transformed = result.fmap_error(|e| format!("Error: {}", e));
assert_eq!(transformed, Err("Error: not found".to_string()));
Sourcefn to_result(self) -> Result<Self::Success, E>
fn to_result(self) -> Result<Self::Success, E>
Converts this type to a Result.
This provides a way to standardize error handling by converting any
error handling type to a Rust Result
.
§Examples
use rustica::utils::error_utils::WithError;
use rustica::datatypes::either::Either;
let either: Either<&str, i32> = Either::left("error");
let result = either.to_result();
assert_eq!(result, Err("error"));
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.