How to handle errors inside a closure that retruns ()

The key problem is how to handle error inside a closure that retruns ().

#[allow(clippy::unwrap_used)]
pub fn backup_newest_in<V: AsRef<[DirEntry]>>(v: V) -> anyhow::Result<()> {
    let mut v = v.as_ref().to_owned();
    if v.is_empty() {
        return Err(anyhow::anyhow!("nothing to backup"));
    }
    //here
    v.sort_by_key(|d: &DirEntry| d.metadata().unwrap().modified().unwrap());
    todo!()
}

can we handle this without unwrap()?

Error handling in situations where we cannot return an error boils down to providing a fallback value.

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!()
}
2 Likes

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.

1 Like

Interestingly, there is actually native support for "reply as a new topic" under that weird arrow at the top right of the reply dialog!

I've yet to find a use case I'm brave enough to actually use it for, though...