Skip to main content

dofigen_lib/
errors.rs

1use std::fmt::Display;
2
3use serde_yaml::Location;
4use thiserror::Error;
5
6pub type Result<T, E = Error> = std::result::Result<T, E>;
7
8#[derive(Error, Debug)]
9pub enum Error {
10    #[error("Error while deserializing the document{loc}: {0}", loc = location_into(.0.location()))]
11    Deserialize(#[from] serde_yaml::Error),
12    #[cfg(feature = "serde_json")]
13    #[error("Error while deserializing JSON: {0}")]
14    DeserializeJSON(#[from] serde_json::Error),
15    #[error("Error while parsing: {0}")]
16    ParseFromStr(#[from] serde::de::value::Error),
17    #[error("Error while parsing bool value: {0}")]
18    ParseBool(#[from] std::str::ParseBoolError),
19    #[error("{0}")]
20    Format(#[from] std::fmt::Error),
21    #[error("{e}", e = report(.0))]
22    Reqwest(#[from] reqwest::Error),
23    #[error("{0}")]
24    Regex(#[from] regex::Error),
25    #[error("{0}")]
26    Custom(String),
27}
28
29impl Error {
30    pub fn display<S: Display>(error: S) -> Self {
31        Self::Custom(format!("{}", error))
32    }
33}
34
35fn location_into(location: Option<Location>) -> String {
36    location
37        .map(|location| format!(" at line {}, column {}", location.line(), location.column()))
38        .unwrap_or_else(|| "".into())
39}
40
41fn report(mut err: &dyn std::error::Error) -> String {
42    let mut s = format!("{}", err);
43    while let Some(src) = err.source() {
44        s.push_str(format!("\n\tCaused by: {}", src).as_str());
45        err = src;
46    }
47    s
48}