You can, and should, also stash the error in a variable so that you can report that at least one error occurred. Compilable example:
use anyhow::Context as _;
use std::{fs, io, time::SystemTime};
pub fn backup_newest_in(v: impl IntoIterator<Item = fs::DirEntry>) -> anyhow::Result<()> {
let mut v: Vec<fs::DirEntry> = Vec::from_iter(v);
if v.is_empty() {
return Err(anyhow::anyhow!("nothing to backup"));
}
let mut sorting_error = Ok(());
v.sort_by_key(|d: &fs::DirEntry| -> SystemTime {
d.metadata()
.and_then(|m| m.modified())
.unwrap_or_else(|error: io::Error| {
sorting_error = Err(error); // save the error
SystemTime::UNIX_EPOCH // placeholder value
})
});
// report a sorting error if there was one
let () = sorting_error.context("failed to read modification dates of some files")?;
todo!()
}
I just noticed that this topic seems to be a continuation of your previous topic How to handle Error? - #9 by BORSXN. Please don’t create separate topics on the same issue (without even linking to previous posts). It makes it harder for people to help you because they don’t have as much context.