How to handle the Error in a While loop?

The code that works if you want to use the ? operator:

while let Some(user_incoming) = incoming.try_next().await? {
   let _ = &users.push(user_incoming);
}

But I want to handle the error locally, not just bubble it up.

So I came up with :

  while let Ok(user_incoming) = incoming.try_next().await {
        if let Some(user_incoming) = user_incoming {
            let _ = &users.push(user_incoming);
        } else {
            println!("We got all user and now got None");
            break;
        }
    }

And although this works without the ? operator. The error could occurr on the
try_next.await ... .

How can I get the error?

Thank you in advance,
Alex

You can use a "manual" loop and pattern matching:

loop {
    match incoming.try_next().await {
        Ok(Some(u)) => users.push(u),
        Ok(None) => break,
        Err(e) => { handle_error(e); break; }
    }
}
4 Likes

Thank you very much! I was looking too far and made it too complicated:(. Your solution is best.

   while let Ok(user_incoming) = incoming
        .try_next()
        .await
        .map_err(|_e| Err::<User, LocalError>(LocalError::CannotGetAllUsers))
    {
        if let Some(user_incoming) = user_incoming {
            let _ = &users.push(user_incoming);
        } else {
            println!("We got all user and now got None");
            break;
        }
    }