在这个极简程序中,我希望 file_size
函数在 Err
中包含路径 /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 crate for that,因为它在处理多种类型时特别方便。在您的情况下,它可能看起来像这样:
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)
关于error-handling - 如何在 Rust 的 IO 错误中包含文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53934888/