From 0c51b4fe419f96241e1204daba6ae6414a00aa6d Mon Sep 17 00:00:00 2001 From: link2xt Date: Mon, 21 Jul 2025 16:27:22 +0000 Subject: [PATCH] docs(STYLE.md): prefer `try_next()` over `next()` --- STYLE.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/STYLE.md b/STYLE.md index 537f9c9db..08a01f792 100644 --- a/STYLE.md +++ b/STYLE.md @@ -78,6 +78,27 @@ All errors should be handled in one of these ways: - With `.log_err().ok()`. - Bubbled up with `?`. +When working with [async streams](https://docs.rs/futures/0.3.31/futures/stream/index.html), +prefer [`try_next`](https://docs.rs/futures/0.3.31/futures/stream/trait.TryStreamExt.html#method.try_next) over `next()`, e.g. do +``` +while let Some(event) = stream.try_next().await? { + todo!(); +} +``` +instead of +``` +while let Some(event_res) = stream.next().await { + todo!(); +} +``` +as it allows bubbling up the error early with `?` +with no way to accidentally skip error processing +with early `continue` or `break`. +Some streams reading from a connection +return infinite number of `Some(Err(_))` +items when connection breaks and not processing +errors may result in infinite loop. + `backtrace` feature is enabled for `anyhow` crate and `debug = 1` option is set in the test profile. This allows to run `RUST_BACKTRACE=1 cargo test`