Provide or_fail() for convenience error conversion.

This commit is contained in:
Yuchen Wu 2024-07-01 11:32:52 -07:00
parent 2d1d1b48d9
commit c4931945ab
2 changed files with 30 additions and 1 deletions

2
.bleep
View file

@ -1 +1 @@
2802f6d492a768ead251828c7eda6fa6115db146
940539c7d0bff45d8182d4eb6c40d099b20ed44e

View file

@ -509,6 +509,13 @@ pub trait OrErr<T, E> {
et: ErrorType,
context: F,
) -> Result<T, BError>;
/// Similar to or_err() but just to surface errors that are not [Error] (where `?` cannot be used directly).
///
/// or_err()/or_err_with() are still preferred because they make the error more readable and traceable.
fn or_fail(self) -> Result<T>
where
E: Into<Box<dyn ErrorTrait + Send + Sync>>;
}
impl<T, E> OrErr<T, E> for Result<T, E> {
@ -537,6 +544,13 @@ impl<T, E> OrErr<T, E> for Result<T, E> {
) -> Result<T, BError> {
self.map_err(|e| Error::explain(et, exp(e)))
}
fn or_fail(self) -> Result<T, BError>
where
E: Into<Box<dyn ErrorTrait + Send + Sync>>,
{
self.map_err(|e| Error::because(ErrorType::InternalError, "", e))
}
}
/// Helper trait to convert an [Option] to an [Error] with context.
@ -641,4 +655,19 @@ mod tests {
" InternalError context: none is an error!"
);
}
#[test]
fn test_into() {
fn other_error() -> Result<(), &'static str> {
Err("oops")
}
fn surface_err() -> Result<()> {
other_error().or_fail()?; // can return directly but want to showcase ?
Ok(())
}
let e = surface_err().unwrap_err();
assert_eq!(format!("{}", e), " InternalError context: cause: oops");
}
}