Skip to content

Instantly share code, notes, and snippets.

@glehmann
Created December 27, 2018 20:54
Show Gist options
  • Save glehmann/b261e7aa22bd01f70501883d97b2f6bd to your computer and use it in GitHub Desktop.
Save glehmann/b261e7aa22bd01f70501883d97b2f6bd to your computer and use it in GitHub Desktop.
adding path to io error in rust, with a trait to ease the error transformation
extern crate custom_error;
use custom_error::custom_error;
use std::fs::metadata;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::result::Result;
custom_error! {ProgramError
Io {
source: io::Error, // we also wrap the source error
path: PathBuf
} = @{format!("{}: {}", path.display(), source)},
// other kinds of error would go there
}
trait ToPathIOErr<T> {
fn with_path(self: Self, path: &Path) -> Result<T, ProgramError>;
}
impl<T> ToPathIOErr<T> for io::Result<T> {
fn with_path(self: Self, path: &Path) -> Result<T, ProgramError> {
self.map_err(|e| ProgramError::Io {
source: e,
path: path.to_path_buf(),
})
}
}
fn file_size(path: &Path) -> Result<u64, ProgramError> {
Ok(metadata(path).with_path(path)?.len())
}
fn main() {
if let Err(err) = file_size(&PathBuf::from("/not/there")) {
eprintln!("{}", err);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment