Created
December 27, 2018 09:47
-
-
Save glehmann/72e0acd5c176e6a3d532433b0d671e61 to your computer and use it in GitHub Desktop.
adding path to io error in rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
see https://stackoverflow.com/questions/53934888/how-to-include-the-file-path-in-an-io-error-in-rust