aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorYuchen Wu <[email protected]>2024-07-01 11:32:52 -0700
committerYuchen Wu <[email protected]>2024-07-12 11:24:29 -0700
commit09b5e03fb180dbf1742938538ebccf0d95586b79 (patch)
tree6470b705e68cc1c125695e03aa529e2fce14ab4c
parent9a68268da5eee2150d34c15e898c5f6cab96d1e8 (diff)
downloadpingora-09b5e03fb180dbf1742938538ebccf0d95586b79.tar.gz
pingora-09b5e03fb180dbf1742938538ebccf0d95586b79.zip
Provide or_fail() for convenience error conversion.
-rw-r--r--.bleep2
-rw-r--r--pingora-error/src/lib.rs29
2 files changed, 30 insertions, 1 deletions
diff --git a/.bleep b/.bleep
index 455674a..c0a9fc9 100644
--- a/.bleep
+++ b/.bleep
@@ -1 +1 @@
-2802f6d492a768ead251828c7eda6fa6115db146 \ No newline at end of file
+940539c7d0bff45d8182d4eb6c40d099b20ed44e \ No newline at end of file
diff --git a/pingora-error/src/lib.rs b/pingora-error/src/lib.rs
index 438b392..d856763 100644
--- a/pingora-error/src/lib.rs
+++ b/pingora-error/src/lib.rs
@@ -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");
+ }
}