Skip to main content

rustapi_view/
error.rs

1//! View error types
2
3use std::fmt;
4
5/// Error type for view/template operations
6#[derive(Debug)]
7pub enum ViewError {
8    /// Template not found
9    TemplateNotFound(String),
10    /// Template rendering failed
11    RenderError(String),
12    /// Template parsing failed
13    ParseError(String),
14    /// Context serialization failed
15    SerializationError(String),
16    /// Template engine not initialized
17    NotInitialized,
18    /// IO error
19    IoError(std::io::Error),
20    /// Tera error
21    Tera(tera::Error),
22}
23
24impl fmt::Display for ViewError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            Self::TemplateNotFound(name) => write!(f, "Template not found: {}", name),
28            Self::RenderError(msg) => write!(f, "Template rendering failed: {}", msg),
29            Self::ParseError(msg) => write!(f, "Template parsing failed: {}", msg),
30            Self::SerializationError(msg) => write!(f, "Context serialization failed: {}", msg),
31            Self::NotInitialized => write!(f, "Template engine not initialized"),
32            Self::IoError(e) => write!(f, "IO error: {}", e),
33            Self::Tera(e) => write!(f, "Tera error: {}", e),
34        }
35    }
36}
37
38impl std::error::Error for ViewError {
39    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
40        match self {
41            Self::IoError(e) => Some(e),
42            Self::Tera(e) => Some(e),
43            _ => None,
44        }
45    }
46}
47
48impl From<std::io::Error> for ViewError {
49    fn from(e: std::io::Error) -> Self {
50        Self::IoError(e)
51    }
52}
53
54impl From<tera::Error> for ViewError {
55    fn from(e: tera::Error) -> Self {
56        Self::Tera(e)
57    }
58}
59
60impl ViewError {
61    /// Create a template not found error
62    pub fn not_found(template: impl Into<String>) -> Self {
63        Self::TemplateNotFound(template.into())
64    }
65
66    /// Create a render error
67    pub fn render_error(msg: impl Into<String>) -> Self {
68        Self::RenderError(msg.into())
69    }
70
71    /// Create a parse error
72    pub fn parse_error(msg: impl Into<String>) -> Self {
73        Self::ParseError(msg.into())
74    }
75
76    /// Create a serialization error
77    pub fn serialization_error(msg: impl Into<String>) -> Self {
78        Self::SerializationError(msg.into())
79    }
80}
81
82impl From<ViewError> for rustapi_core::ApiError {
83    fn from(err: ViewError) -> Self {
84        match err {
85            ViewError::TemplateNotFound(name) => {
86                rustapi_core::ApiError::internal(format!("Template not found: {}", name))
87            }
88            ViewError::NotInitialized => {
89                rustapi_core::ApiError::internal("Template engine not initialized")
90            }
91            _ => rustapi_core::ApiError::internal(err.to_string()),
92        }
93    }
94}