For a long time I've been struggling with expressing retryable vs fatal errors. The context in this specific case is that I'm writing code within a "Connector" that will keep looping if an error is "retryable", or terminate if it is not. To reiterate: The actual retrying is already handled, I need some way to, within a function, pick and choose which failures are retryable or not. The primary goal is ergonomics and avoiding a lot of boiler-plate within the functions whose function calls may be retryable or fatal.
I've been trying different ways to look at it over the years, and I've ended up with a wrapper around the E type in Result<T, E>:
#[derive(Debug, Clone, PartialEq, Eq)] pub struct MaybeRetry<E> { retryable: bool, inner: E } impl<E> MaybeRetry<E> { pub fn retry(err: E) -> Self { Self { retryable: true, inner: err } } pub fn fatal(err: E) -> Self { Self { retryable: false, inner: err } } pub fn is_retryable(&self) -> bool { self.retryable } pub fn into_inner(self) -> E { self.inner } } impl<E: fmt::Display> fmt::Display for MaybeRetry<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.inner) } } impl<E: std::error::Error + 'static> std::error::Error for MaybeRetry<E> { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.inner) } } /// Default to fatal on `?` so unannotated errors fail fast. impl<E> From<E> for MaybeRetry<E> { fn from(err: E) -> Self { Self::fatal(err) } } impl<E> AsRef<E> for MaybeRetry<E> { fn as_ref(&self) -> &E { &self.inner } } /// Convenience extension trait pub trait RetryExt<T, E> { fn retry_err(self) -> Result<T, MaybeRetry<E>>; fn fatal_err(self) -> Result<T, MaybeRetry<E>>; } impl<T, E> RetryExt<T, E> for Result<T, E> { fn retry_err(self) -> Result<T, MaybeRetry<E>> { self.map_err(MaybeRetry::retry) } fn fatal_err(self) -> Result<T, MaybeRetry<E>> { self.map_err(MaybeRetry::fatal) } } This allows expressing mixed fatal and retryable calls in a function as such:
fn restore_session(addr: &str) -> Result<(), MaybeRetry<Error>> { let state = load_session_state().map_err(Error::from).fatal_err()?; connect(addr, Some(state)).map_err(Error::from).retry_err()?; Ok(()) } While this is better than what I started out with, I have a gut feeling that there are better ways to do this, and also the .map_err(Error::from) makes me sad. I've been staring at this for too long, and I realize that I need some outside input.
How would you solve this specific problem? (I.e. mixing retryable/fatal errors back to a caller). Not necessary looking for improvements to MaybeRetry -- a complete ?REDO FROM START is an option.
10 posts - 7 participants
