Rust file open error handling

How do i output my error message when a file im trying to open is not found instead of "Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }"

use std::fs::File;
fn main() -> std::io::Result<()>{
    
    let mut file = File::open("foo.txt")?;   
    
    Ok(())
}
fn main() {
    let file = match File::open("foo.txt") {
        Ok(file) => file,
        Err(err) => {
            println!("my error message: {}", err);
            std::process::exit(1);
        }
    };
}
2 Likes

Another possible solution without an explicit exit:

use std::fs::File;

fn main() -> Result<(), &'static str> {
   let mut file = File::open("foo.txt").map_err(|_| "Please specify a valid file name")?;

   … work with `file` …

    Ok(())
}

(Anything can work as the error type of the Result return value of main() as long as it implements Debug).

1 Like

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.