From c4931945ab31e513bf998510ecc5412fde2a5c34 Mon Sep 17 00:00:00 2001 From: Yuchen Wu Date: Mon, 1 Jul 2024 11:32:52 -0700 Subject: [PATCH] Provide or_fail() for convenience error conversion. --- .bleep | 2 +- pingora-error/src/lib.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) 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 { et: ErrorType, context: F, ) -> Result; + + /// 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 + where + E: Into>; } impl OrErr for Result { @@ -537,6 +544,13 @@ impl OrErr for Result { ) -> Result { self.map_err(|e| Error::explain(et, exp(e))) } + + fn or_fail(self) -> Result + where + E: Into>, + { + 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"); + } }