1use std::error;
2use std::fmt::{self, Formatter};
3use std::path::{Path, PathBuf};
4
5use crate::docfs::PathError;
6
7#[derive(Debug)]
8pub(crate) struct Error {
9 pub(crate) file: PathBuf,
10 pub(crate) error: String,
11}
12
13impl error::Error for Error {}
14
15impl std::fmt::Display for Error {
16 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
26impl PathError for Error {
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]
36macro_rules! try_none {
37 ($e:expr, $file:expr) => {{
38 use std::io;
39 match $e {
40 Some(e) => e,
41 None => {
42 return Err(<$crate::error::Error as $crate::docfs::PathError>::new(
43 io::Error::new(io::ErrorKind::Other, "not found"),
44 $file,
45 ));
46 }
47 }
48 }};
49}
50
51#[macro_export]
52macro_rules! try_err {
53 ($e:expr, $file:expr) => {{
54 match $e {
55 Ok(e) => e,
56 Err(e) => return Err(Error::new(e, $file)),
57 }
58 }};
59}