1 use std::error; 2 use std::fmt::{self, Formatter}; 3 use std::path::{Path, PathBuf}; 4 5 use crate::docfs::PathError; 6 7 #[derive(Debug)] 8 crate struct Error { 9 crate file: PathBuf, 10 crate error: String, 11 } 12 13 impl error::Error for Error {} 14 15 impl std::fmt::Display for Error { fmt(&self, f: &mut Formatter<'_>) -> fmt::Result16 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 17 let file = self.file.display().to_string(); 18 if file.is_empty() { 19 write!(f, "{}", self.error) 20 } else { 21 write!(f, "\"{}\": {}", self.file.display(), self.error) 22 } 23 } 24 } 25 26 impl PathError for Error { new<S, P: AsRef<Path>>(e: S, path: P) -> Error where S: ToString + Sized,27 fn new<S, P: AsRef<Path>>(e: S, path: P) -> Error 28 where 29 S: ToString + Sized, 30 { 31 Error { file: path.as_ref().to_path_buf(), error: e.to_string() } 32 } 33 } 34 35 #[macro_export] 36 macro_rules! try_none { 37 ($e:expr, $file:expr) => {{ 38 use std::io; 39 match $e { 40 Some(e) => e, 41 None => { 42 return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"), $file)); 43 } 44 } 45 }}; 46 } 47 48 #[macro_export] 49 macro_rules! try_err { 50 ($e:expr, $file:expr) => {{ 51 match $e { 52 Ok(e) => e, 53 Err(e) => return Err(Error::new(e, $file)), 54 } 55 }}; 56 } 57