trust_dns_server/error/
config_error.rs

1// Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use std::{fmt, io};
9
10use thiserror::Error;
11
12#[cfg(feature = "backtrace")]
13use crate::proto::{trace, ExtBacktrace};
14
15/// An alias for results returned by functions of this crate
16pub type Result<T> = ::std::result::Result<T, Error>;
17
18/// The error kind for errors that get returned in the crate
19#[derive(Debug, Error)]
20#[non_exhaustive]
21pub enum ErrorKind {
22    // foreign
23    /// An error got returned from IO
24    #[error("io error: {0}")]
25    Io(#[from] io::Error),
26
27    /// An error occurred while decoding toml data
28    #[error("toml decode error: {0}")]
29    TomlDecode(#[from] toml::de::Error),
30
31    /// An error occurred while parsing a zone file
32    #[error("failed to parse the zone file: {0}")]
33    ZoneParse(#[from] crate::proto::serialize::txt::ParseError),
34}
35
36/// The error type for errors that get returned in the crate
37#[derive(Debug)]
38pub struct Error {
39    kind: Box<ErrorKind>,
40    #[cfg(feature = "backtrace")]
41    backtrack: Option<ExtBacktrace>,
42}
43
44impl Error {
45    /// Get the kind of the error
46    pub fn kind(&self) -> &ErrorKind {
47        &self.kind
48    }
49}
50
51impl fmt::Display for Error {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        cfg_if::cfg_if! {
54            if #[cfg(feature = "backtrace")] {
55                if let Some(ref backtrace) = self.backtrack {
56                    fmt::Display::fmt(&self.kind, f)?;
57                    fmt::Debug::fmt(backtrace, f)
58                } else {
59                    fmt::Display::fmt(&self.kind, f)
60                }
61            } else {
62                fmt::Display::fmt(&self.kind, f)
63            }
64        }
65    }
66}
67
68impl<E> From<E> for Error
69where
70    E: Into<ErrorKind>,
71{
72    fn from(error: E) -> Self {
73        let kind: ErrorKind = error.into();
74
75        Self {
76            kind: Box::new(kind),
77            #[cfg(feature = "backtrace")]
78            backtrack: trace!(),
79        }
80    }
81}