How jump a error and continue?

Hi, i have this function that return the last file modification from folder, but if folder is empty it give me an error, how jump and continue ?

fn last_modified(src: &String) -> io::Result<String> {
    let current_dir = src;
    let last_modified_file = std::fs::read_dir(current_dir)
        .expect("Couldn't access local directory")
        .flatten() // Remove failed
        .filter(|f| f.metadata().unwrap().is_file()) // Filter out directories (only consider files)
        .max_by_key(|x| x.metadata().unwrap().modified().unwrap()); // Get the most recently modified file
    //println!("Most recent file: {:?}", last_modified_file); // :)        
    let path = last_modified_file.expect("REASON").path();    
    return Ok(path.file_stem().expect("REASON").to_str().unwrap().to_string())
}

let last_modified_file = match last_modified(&novel_path.display().to_string()) {
                                Ok(last) => last,
                                _ => continue,                                
};

ERROR OUTPUT:
thread 'main' panicked at 'Couldn't access local directory: Os { code: 2, kind: NotFound, message: "No such file or di
rectory" }', src/main.rs:349:10
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

Generally, we'll rely on expect when we as the developer of this code can guarantee that the value will be an Ok variant indicating success on an operation with potential for a recoverable error that we've already guaranteed won't occur.

There doesn't appear to be logic here to ensure that the file will exist before calling expect, so you'll want to handle scenarios of success and error state of the call to read_dir.

If you want the Err to be returned as early as possible, then it would make sense to use the ? syntactic sugar in place of directly unwrapping with expect. The use of question mark is to unwrap if an Ok variant and to use the value as function return if it's an Err variant.

If you'd like more, you can refer to the book.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.