expression

Axum: handle a late body stream error

A body may fail after some data is available. If headers have already been sent, a server cannot replace them with a fresh error status. Consumers should check each result and distinguish complete content from interrupted content. The in-memory test receives one successful piece followed by an error. In-memory standalone Cargo example. Expected stdout (not executed): first: 4 failed: true Common mistake: Treating a successful HTTP status as proof that the entire streamed body arrived.

Formal Syntax & Structure

rust syntaxrust
Stream<Item = Result<Bytes, E>>

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::body::Bytes;    use futures_util::{stream, StreamExt};    let body = Body::from_stream(stream::iter([Ok(Bytes::from_static(b"part")), Err(std::io::Error::other("synthetic failure"))]));    let mut data = body.into_data_stream();    println!("first: {}", data.next().await.unwrap().unwrap().len());    println!("failed: {}", data.next().await.unwrap().is_err());}
Rust Reference