Skip to content

Instantly share code, notes, and snippets.

@glehmann
Created December 27, 2018 09:47
Show Gist options
  • Save glehmann/72e0acd5c176e6a3d532433b0d671e61 to your computer and use it in GitHub Desktop.
Save glehmann/72e0acd5c176e6a3d532433b0d671e61 to your computer and use it in GitHub Desktop.
adding path to io error in rust
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}: {source}", source=source, path=path.display())},
// other kinds of error would go there
}
fn file_size(path: &Path) -> Result<u64, ProgramError> {
match metadata(path) {
Ok(md) => Ok(md.len()),
Err(e) => Err(ProgramError::Io {
source: e,
path: path.to_path_buf(),
}),
}
}
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