Expand description
Collect all the errors from an iterator of Result
s
into a Result
with a single Error
: Result<T, Error>
.
The resultant Error has an error message with all the errors’ messages each on a newline.
The chain of causes for each error is retained with anyhow’s inline representation, where causes are separated by colons.
Examples:
use anyhow::{anyhow, Result, Context};
use beau_collector::BeauCollector as _;
let x = vec![Ok(()), Err(anyhow!("woops")).context("There was an error"), Err(anyhow!("woops again"))];
let y: Result<Vec<()>> = x.into_iter().bcollect();
assert_eq!(y.unwrap_err().to_string(), "There was an error: woops\nwoops again")
,
use anyhow::{anyhow, Result};
use std::collections::HashMap;
use beau_collector::BeauCollector as _;
let x = vec!["one", "two", "three", "four"];
let y = x
.iter()
.map(|name: &&str| -> Result<(String, usize)> {
let length = name.len();
if length < 4 {
Ok((name.to_string(), length))
} else {
Err(anyhow!("name \"{}\" has {} characters", name, length))
}
})
// Turbofish ::<> gives the type to be collected into the Ok()
// variant of the Result.
.bcollect::<HashMap<_, _>>();
assert_eq!(
y.unwrap_err().to_string(),
"name \"three\" has 5 characters\nname \"four\" has 4 characters")