How to Handle Errors in Iterator Chains

Handle errors in Rust iterator chains using `?` for propagation or `filter_map` to skip invalid items gracefully.

Handle errors in iterator chains by using the ? operator to propagate Result types or methods like filter_map to skip invalid items. This approach avoids panicking and allows the chain to continue processing remaining elements gracefully.

let numbers = vec![1, 2, 3, 4, 5];
let results: Result<Vec<i32>, &str> = numbers
    .iter()
    .map(|&n| if n % 2 == 0 { Ok(n * 2) } else { Err("odd number") })
    .collect();

match results {
    Ok(v) => println!("Success: {:?}", v),
    Err(e) => println!("Error: {}", e),
}

Alternatively, use filter_map to skip errors entirely:

let numbers = vec![1, 2, 3, 4, 5];
let results: Vec<i32> = numbers
    .iter()
    .filter_map(|&n| if n % 2 == 0 { Some(n * 2) } else { None })
    .collect();

println!("Filtered results: {:?}", results);