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
/*!
All of the error types returned by Templar.
 */

use std::error::Error;
use std::fmt;
use std::sync::Arc;

/// This is the primary error type for template
#[derive(Debug, Clone)]
pub enum TemplarError {
    /// Some error occurred while parsing a template
    ParseFailure(String),
    /// Some error occurred while rendering a template
    RenderFailure(String),
    /// Error occurred while manipulating the context
    ContextFailure(String),
    /// Filter referred to by template is not available
    FilterNotFound(String),
    /// Function referred to by template is not available
    FunctionNotFound(String),
    /// An I/O error occurred
    IO(String),
    /// Some other error, check the inner value
    Other(Arc<Box<dyn Error + Send + Sync>>),
}

impl fmt::Display for TemplarError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TemplarError::ParseFailure(s) => write!(f, "Could not parse template. {}", s),
            TemplarError::RenderFailure(s) => write!(f, "Could not render template. {}", s),
            TemplarError::ContextFailure(s) => write!(f, "Could not update context. {}", s),
            TemplarError::FilterNotFound(s) => write!(
                f,
                "Filter '{}' was not found while building this expression",
                s
            ),
            TemplarError::FunctionNotFound(s) => write!(
                f,
                "Function '{}' was not found while building this expression",
                s
            ),
            TemplarError::IO(s) => write!(f, "An IO Error occurred. {}", s),
            TemplarError::Other(e) => e.fmt(f),
        }
    }
}

impl Error for TemplarError {}

/// Result type for all Templar methods
pub type Result<T> = std::result::Result<T, TemplarError>;

impl From<Box<dyn Error + Send + Sync>> for TemplarError {
    fn from(e: Box<dyn Error + Send + Sync>) -> TemplarError {
        TemplarError::Other(Arc::new(e))
    }
}

/// Helper trait for wrapping other error types as a Templar error
pub trait ResultMap<U> {
    /// Wrap an external error as a Templar error
    fn wrap(self) -> Result<U>;
}

impl<U, T> ResultMap<U> for std::result::Result<U, T>
where
    T: std::error::Error + Into<Box<dyn Error + Send + Sync>>,
{
    fn wrap(self) -> Result<U> {
        self.map_err(|e| TemplarError::Other(Arc::new(e.into())))
    }
}

impl From<std::io::Error> for TemplarError {
    fn from(e: std::io::Error) -> TemplarError {
        TemplarError::IO(e.to_string())
    }
}