How to get "message" field out of std::io::error

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)

Please follow our formatting guidelines:

1 Like

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?

1 Like

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).

The message part is not exposed: - source

You can write your own error message, e.g.:

match err.kind() {
   io::ErrorKind::NotFound => eprintln!("File not found: {}", filename),
   _ => eprintln!("Something else failed! ({})", err),

or use .map_err(|err| format!(…))? if you're inside a function that returns Result.


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.