Expressing retryable vs fatal errors to caller

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.

Couldn't you have a helper funnction that wraps the error in fatal/retry and converts the error in one call?

e.g.

pub trait RetryExt<T, E> {
  fn retry_err(self) -> Result<T, MaybeRetry<E>>;
  fn fatal_err(self) -> Result<T, MaybeRetry<E>>;

  fn into_retry_err<B>(self) -> Result<T, MaybeRetry<B>>
  where
    E: Into<B>,
  ;
  fn into_fatal_err<B>(self) -> Result<T, MaybeRetry<B>>
  where
    E: Into<B>,
  ;
}

I'd advice against this,
accidentally making a non-fatal error fatal because you forgot .retry_err seems much worse
than getting a compilation error (that can be fixed in 10 seconds) because you forgot .fatal_err() to me

[Edit: I saw Miro's solution afterwards, which is similar and cleaner]

What prevents you to do something like this, with appropriate free function (or even Maybe retry::fatal)?

fn restore_session(addr: &str) -> Result<(), MaybeRetry<Error>> {
  let state = load_session_state().map_err(fatal)?;
  connect(addr, Some(state)).map_err(retry)?;
  Ok(())
}

Another idea would be to change MaybeRetry::fatal to a generic that accepts any error that is Into<E>.

(Sorry, on the phone I cannot develop or test much more.)

(A couple off-topic asides.)

Error outputters that show the error chain will show the inner error twice with the above; I recommend

   fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
-    Some(&self.inner)
     self.inner.source()
   }

(or more generally: if you display the inner error, return inner.source(); if you don't, use Some(&self.inner)).

And independently[1]

   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-    write!(f, "{}", self.inner)
+    // Preserve the formatting flags passed in
+    self.inner.fmt(f)
   }

(Loss of flags is illustrated by stdout in the playground.)


  1. if you're not just passing through this is a bigger pain to make nice ↩︎

Yeah, you're definitely right.

I gotta keep in mind that, more of then than not, explicit is better.

What about something like

trait Retriable {
  fn is_retriable(&self) -> bool;
}

Your retry logic could then accept any Fn() -> Result<T, E> where E: Retriable holds. You'd need to provide a Retriable impl for any error types that are used in that context; some of them will be trivial:

impl Retriable for std::io::Error {
  fn is_retriable(&self) -> bool {
    match self.kind() {
      ErrorKind::ConnectionAborted |
      ErrorKind::ConnectionReset /* | … */ => true,
      _ => false,
    }
  }
}

Some may depend intimately on the logic of the error, and some may even be provided by a wrapper that implements Retriable for an arbitrary inner type, the way your MaybeRetry does.

What if identical errors are either retriable or fatal depending on where they happened?

In that case, perhaps the errors should not be identical.

I'd also to add a number of retries until give up and a delay between reties which can be a static or grow with an attempt number. So, the wrapper should work with any fn returning Result. Perhaps some Err can be also not suitable for retry, so it can be valuable to specify that as well.