Skip to main content

dns_mail_discover/
error.rs

1use std::{error, fmt::Display, io::Error as IoError, result};
2
3use trust_dns_resolver::error::ResolveError;
4
5macro_rules! impl_from_error {
6    ($error_type:ty, $error_kind:expr, $error_msg:expr) => {
7        impl From<$error_type> for Error {
8            fn from(err: $error_type) -> Self {
9                Error::new($error_kind(err), $error_msg)
10            }
11        }
12    };
13}
14
15macro_rules! err {
16    ($kind:expr, $($arg:tt)*) => {{
17		use crate::error::Error;
18
19        let kind = $kind;
20        let message = format!($($arg)*);
21        return Err(Error::new( kind, message ));
22    }};
23}
24
25#[derive(Debug)]
26pub enum ErrorKind {
27    NoBytesSent,
28    Unresolvable,
29    NotFound,
30    Io(IoError),
31    Resolve(ResolveError),
32}
33
34#[derive(Debug)]
35pub struct Error {
36    kind: ErrorKind,
37    message: String,
38}
39
40impl_from_error!(
41    ResolveError,
42    |err| ErrorKind::Resolve(err),
43    "Failed to resolve dns query"
44);
45impl_from_error!(IoError, |err| ErrorKind::Io(err), "IO error");
46
47impl Display for Error {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        write!(f, "{}", self.message)
50    }
51}
52
53impl Error {
54    pub fn new<M: Into<String>>(kind: ErrorKind, message: M) -> Self {
55        Self {
56            kind,
57            message: message.into(),
58        }
59    }
60
61    pub fn kind(&self) -> &ErrorKind {
62        &self.kind
63    }
64}
65
66impl error::Error for Error {}
67
68pub(crate) use err;
69
70pub type Result<T> = result::Result<T, Error>;