5

The canonical example of a Warp rejection handler is

async fn handle_rejection(err: Rejection) -> Result<impl Reply, Infallible> {

But what's the advantage of a Result<ok, err> such that the err is Infallible and can never be reached? Why not just return an impl Reply?

Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • 1
    It's mostly useful for generic programming, e.g. where a trait can return an error using an associated type, but may not actually represent a fallible operation. – apetranzilla Jun 04 '21 at 03:23

1 Answers1

14

It usually means one of two things:

  • The function is part of a trait, and the trait declaration indicates that the method can fail and return a Result<T, E>. Now, some implementations of that trait might happen not to have a fail path, and use an Infallible-like type for E.

    A standard library example of this is the FromStr trait. FromStr can obviously fail when implemented on u32, but not when implemented on String. Therefore impl FromStr for String uses std::convert::Infallible for its error case.

  • The function is going to be used in a context that expects a fallible function.

    This is the case in your example. handle_rejection is passed to warp::Filter::recover, which expects a fallible function. This makes sense as not all errors are recoverable, therefore recover might still have to deal with these.

    Now, this is a toy example that happens to be able to handle all errors, and therefore use Infallible.

mcarton
  • 27,633
  • 5
  • 85
  • 95