| 1 | //! Common error type for file operations. |
| 2 | |
| 3 | use std::error::Error; |
| 4 | use std::fmt; |
| 5 | use std::io; |
| 6 | use std::path::{Path, PathBuf}; |
| 7 | |
| 8 | /// Common error type for file operations. |
| 9 | #[derive(Debug)] |
| 10 | pub(crate) struct FileError { |
| 11 | path: PathBuf, |
| 12 | source: io::Error, |
| 13 | } |
| 14 | |
| 15 | impl FileError { |
| 16 | /// Returns a new `io::Error` backed by a `FileError`. |
| 17 | pub fn new<P: AsRef<Path>>(path: P, source: io::Error) -> io::Error { |
| 18 | io::Error::new(source.kind(), FileError { |
| 19 | path: path.as_ref().into(), |
| 20 | source, |
| 21 | }) |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | impl fmt::Display for FileError { |
| 26 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 27 | write!(f, "Reading {:?}: {}", self.path.display(), self.source) |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | impl Error for FileError { |
| 32 | fn source(&self) -> Option<&(dyn Error + 'static)> { |
| 33 | Some(&self.source) |
| 34 | } |
| 35 | } |