简体   繁体   中英

How to include the file path in an IO error in Rust?

In this minimalist program, I'd like the file_size function to include the path /not/there in the Err so it can be displayed in the main function:

use std::fs::metadata;
use std::io;
use std::path::Path;
use std::path::PathBuf;

fn file_size(path: &Path) -> io::Result<u64> {
    Ok(metadata(path)?.len())
}

fn main() {
    if let Err(err) = file_size(&PathBuf::from("/not/there")) {
        eprintln!("{}", err);
    }
}

You must define your own error type in order to wrap this additional data.

Personally, I like to use the custom_error crate for that, as it's especially convenient for dealing with several types. In your case it might look like this:

use custom_error::custom_error;
use std::fs::metadata;
use std::io;
use std::path::{Path, PathBuf};
use std::result::Result;

custom_error! {ProgramError
    Io {
        source: io::Error,
        path: PathBuf
    } = @{format!("{path}: {source}", source=source, path=path.display())},
}

fn file_size(path: &Path) -> Result<u64, ProgramError> {
    metadata(path)
        .map(|md| md.len())
        .map_err(|e| ProgramError::Io {
            source: e,
            path: path.to_path_buf(),
        })
}

fn main() {
    if let Err(err) = file_size(&PathBuf::from("/not/there")) {
        eprintln!("{}", err);
    }
}

Output:

/not/there: No such file or directory (os error 2)

While Denys Séguret's answer is correct, I like using my crate SNAFU because it provides the concept of a context . This makes the act of attaching the path (or anything else!) very easy to do:

use snafu::{ResultExt, Snafu}; // 0.2.3
use std::{
    fs, io,
    path::{Path, PathBuf},
};

#[derive(Debug, Snafu)]
enum ProgramError {
    #[snafu(display("Could not get metadata for {}: {}", path.display(), source))]
    Metadata { source: io::Error, path: PathBuf },
}

fn file_size(path: impl AsRef<Path>) -> Result<u64, ProgramError> {
    let path = path.as_ref();
    let md = fs::metadata(&path).context(Metadata { path })?;
    Ok(md.len())
}

fn main() {
    if let Err(err) = file_size("/not/there") {
        eprintln!("{}", err);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM