1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
use crate::configuration::{CompoundKey, Key, NodeType};
use serde::de;
use std::{convert::From, fmt::Display, ops::Deref};

/// Represents all errors that might occur at all stages of processing configuration.
#[derive(Debug)]
pub struct ConfigurationError {
    inner: Box<ErrorImpl>,
}

/// Underlying implementation of [`ConfigurationError`](ConfigurationError).
#[derive(Debug)]
pub struct ErrorImpl {
    code: ErrorCode,
    context: Option<Vec<String>>,
    path: Option<Vec<Key>>,
}

/// Describes underlying cause of error.
#[derive(Debug)]
pub enum ErrorCode {
    /// Informs that operation is not valid for given node type e.g descending into value node.
    WrongNodeType(NodeType, NodeType),
    /// Informs that it is not possible to convert value present in configuration to desired type.
    WrongValueType(String, String),
    /// Informs that requested index from array kept in configuration exceeds bounds of the array.
    IndexOutOfRange(usize),
    /// Informs that key specified while accessing configuration is of wrong type.
    /// Might occur when trying to e.g index into map.
    WrongKeyType(NodeType, String),
    /// Informs that requested key is not present in a configuration.
    KeyNotFound(String),
    /// Informs about errors during merging configuration nodes.
    /// Might occur in circumstances like merging map node with array node.
    BadNodeMerge(NodeType, NodeType),
    /// Informs about different kinds of input/output errors.
    /// Occurs mostly during source collection e.g. reading file or downloading content over network.
    IoError(std::io::Error),
    /// Informs about errors during deserialization.
    /// It covers both external sources and internal structures deserialization.
    DeserializationError(String),
    /// Informs about error attributable to executing invalid operations on empty configuration.
    EmptyConfiguration,
    /// Informs about errors attributable to invalid operation on null value.
    NullValue,
    /// Informs about parsing error that occured.
    ParsingError(String),
}

impl ConfigurationError {
    /// Returns reference to underlying error code.
    /// Returned object has all contextual information stripped off.
    pub fn inner(&self) -> &ErrorCode {
        &self.inner.code
    }

    /// Enriches error context with arbitray message.
    ///
    /// Used to put more contextual information in the error to facilitate debugging issues.
    /// One can put e.g. path to file that failed to open in error message this way.
    ///
    ///# Example
    ///```rust
    ///use miau::error::{ConfigurationError, ErrorCode};
    ///
    ///let error: ConfigurationError = ErrorCode::NullValue.into();
    ///
    ///let enriched_error = error
    ///    .enrich_with_context("Detailed description of contextual information");
    ///```
    pub fn enrich_with_context<T: Display>(mut self, message: T) -> Self {
        match self.inner.context {
            Some(ref mut context) => context.push(message.to_string()),
            None => {
                self.inner.context = Some(vec![message.to_string()]);
            }
        }
        self
    }

    /// Enriches error context with a key.
    ///
    /// Used to put more contextual information in the error to facilitate debugging issues.
    /// One can put information about location in configuration tree in error with this function.
    ///
    ///# Example
    ///```rust
    ///use miau::error::{ConfigurationError, ErrorCode};
    ///use miau::configuration::Key;
    ///
    ///let error: ConfigurationError = ErrorCode::NullValue.into();
    ///
    ///let enriched_error = error
    ///    .enrich_with_key(Key::Map("key".to_string()));
    ///```
    pub fn enrich_with_key(mut self, key: Key) -> Self {
        match self.inner.path {
            Some(ref mut path) => {
                path.push(key);
            }
            None => {
                self.inner.path = Some(vec![key]);
            }
        }
        self
    }

    /// Enriches error context with a complex path.
    ///
    /// Used to put more contextual information in the error to facilitate debugging issues.
    /// One can put information about location in configuration tree in error with this function.
    pub fn enrich_with_keys(mut self, keys: &CompoundKey) -> Self {
        if self.inner.path.is_none() {
            self.inner.path = Some(Vec::new());
        }

        let path = self.inner.path.as_mut().unwrap();

        // this rev() is a nasty hack to ensure ordering
        for key in keys.iter().rev() {
            path.push(key.clone());
        }

        self
    }

    /// Returns an object that displays error in pretty way.
    ///
    ///# Example
    ///```rust
    ///use miau::error::{ConfigurationError, ErrorCode};
    ///use miau::configuration::Key;
    ///
    ///let error: ConfigurationError = ErrorCode::NullValue.into();
    ///
    ///println!("Basic display : {}", error);
    ///println!("Pretty display : {}", error.pretty_display());
    ///```
    pub fn pretty_display(&self) -> PrettyConfigurationDisplay {
        PrettyConfigurationDisplay(self)
    }
}

impl ErrorImpl {
    /// Returns reference to underlying cause of the error.
    pub fn get_code(&self) -> &ErrorCode {
        &self.code
    }

    /// Returns path in configuration at which error occured.
    ///
    /// Returned value is a slice with configuration keys counting from root.
    pub fn get_path(&self) -> Option<&[Key]> {
        if let Some(ref path) = self.path {
            Some(path)
        } else {
            None
        }
    }

    /// Returns additional context attached to error.
    ///
    /// This information can contain, for instance, name of the file that was not found.
    pub fn get_context(&self) -> Option<&[String]> {
        if let Some(ref context) = self.context {
            Some(context)
        } else {
            None
        }
    }
}

struct KeyVec<'v>(&'v [Key]);

impl<'v> Display for KeyVec<'v> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut first = true;
        for key in self.0.iter().rev() {
            if first {
                write!(f, "{}", key)?;
                first = false;
                continue;
            }
            write!(f, "-->{}", key)?;
        }
        Ok(())
    }
}

impl Display for ConfigurationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", &self.inner.code)?;

        if let Some(ref path) = self.inner.path {
            write!(f, ". Path : {}", KeyVec(path))?;
        }

        if let Some(ref context) = self.inner.context {
            write!(f, ". Context: ")?;
            for msg in context.iter() {
                write!(f, "| {} |", msg)?;
            }
        }

        Ok(())
    }
}

///Wrapper that displays in a pretty way.
///
///Not of any other use besides that.
pub struct PrettyConfigurationDisplay<'e>(&'e ConfigurationError);

impl<'e> Display for PrettyConfigurationDisplay<'e> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{}", &self.0.inner.code)?;

        if let Some(ref path) = self.0.inner.path {
            writeln!(f, "Path : {}", KeyVec(path))?;
        }

        if let Some(ref context) = self.0.inner.context {
            writeln!(f, "Context: ")?;
            for msg in context.iter() {
                writeln!(f, "\t{}", msg)?;
            }
        }

        Ok(())
    }
}

impl Display for ErrorCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ErrorCode::WrongNodeType(exp, act) => {
                write!(f, "Unexpected node type. Expected {}, got {}", exp, act)
            }
            ErrorCode::WrongValueType(exp, act) => {
                write!(f, "Unexpected value type. Expected {}, got {}", exp, act)
            }
            ErrorCode::IndexOutOfRange(i) => write!(f, "Index {} exceeds bounds of the array.", i),
            ErrorCode::WrongKeyType(ntype, k) => {
                write!(f, "Cannot access {} with key `{}`", ntype, k)
            }
            ErrorCode::KeyNotFound(k) => write!(f, "Unable to find key {}.", k),
            ErrorCode::BadNodeMerge(a, b) => {
                write!(f, "It is forbidden to substitute {} for {}", b, a)
            }
            ErrorCode::IoError(e) => write!(f, "I/O error occurred. {}", e),
            ErrorCode::DeserializationError(e) => write!(f, "Deserialization error occured. {}", e),
            ErrorCode::NullValue => write!(f, "Expected non-null value"),
            ErrorCode::EmptyConfiguration => write!(f, "Expected non-empty configuration"),
            ErrorCode::ParsingError(msg) => write!(f, "Parsing error. {}", msg),
        }
    }
}

impl Deref for ConfigurationError {
    type Target = ErrorImpl;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl std::error::Error for ConfigurationError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self.inner.code {
            ErrorCode::IoError(ref e) => Some(e),
            _ => None,
        }
    }
}

impl From<std::io::Error> for ConfigurationError {
    fn from(e: std::io::Error) -> Self {
        ConfigurationError::from(ErrorCode::IoError(e))
    }
}

impl From<ErrorCode> for ConfigurationError {
    fn from(e: ErrorCode) -> Self {
        ConfigurationError {
            inner: Box::new(ErrorImpl {
                code: e,
                context: None,
                path: None,
            }),
        }
    }
}

impl de::Error for ConfigurationError {
    fn custom<T>(msg: T) -> Self
    where
        T: Display,
    {
        ConfigurationError::from(ErrorCode::DeserializationError(msg.to_string()))
    }
}