Skip to main content

rustdoc/
error.rs

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