簡體   English   中英

如何在Rust中的IO錯誤中包含文件路徑?

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

在這個極簡主義程序中,我希望file_size函數在Err包含path /not/there ,以便它可以顯示在main函數中:

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);
    }
}

您必須定義自己的錯誤類型才能包裝此附加數據。

就個人而言,我喜歡使用custom_error包,因為它對於處理幾種類型特別方便。 在您的情況下,它可能看起來像這樣:

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);
    }
}

輸出:

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

雖然DenysSéguret的答案是正確的,但我喜歡使用我的箱子SNAFU,因為它提供了上下文的概念。 這使得附加路徑(或其他任何東西!)的行為非常容易:

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM