When I get an error trying to open a file, I want to print only the "message" field out of the resulting std::io::error, but I can't seem to do it. In the following program I print the message and the error number, but I want to print only the message.
use std::fs;
use std::io;
use std::io::BufRead;
fn main(){
let filename = "badfilename";
let f = fs::File::open(filename);
if let Some(err) = f.as_ref().err() {
println!("Can't open file: {}", err);
} else {
let mut buffer= String::new();
let mut reader= io::BufReader::new(f.unwrap());
reader.read_line(&mut buffer).unwrap();
}
}
Executing this gives:
Can't open file: No such file or directory (os error 2)
You can't. There is no real message field and the display format is not customizable. You could perhaps match on known errors and provide your own message?
You'll have to convert into text explicitly before you can do anything with it:
if let Some(err) = f.as_ref().err() {
if err.to_string().contains("os error 2") {
println!("Can't open file: no file found.");
} // err.to_string() is what you're looking for
}
Please don't check to_string(). That's inefficient and unreliable (the wording of the message may change).
There's .kind() method on io::Error that quickly and reliably returns ErrorKind::NotFound.
If you're looking for the OS-specific error code, then .raw_os_error() will return you Some(2).