Skip to main content

docx_templating/
error.rs

1//! Error types for the docx-templating library.
2//!
3//! This module defines the top-level [`enum@Error`] enum and domain-specific error types.
4
5use crate::domain::engine::RenderError;
6use thiserror::Error;
7
8/// Result type alias for docx-templating operations.
9pub type Result<T> = std::result::Result<T, Error>;
10
11/// Top-level error type for docx-templating.
12///
13/// This enum wraps domain-specific errors and provides automatic conversions
14/// via `From` implementations powered by `thiserror`.
15#[derive(Debug, Error)]
16#[non_exhaustive]
17pub enum Error {
18    /// I/O error (file operations, ZIP reading/writing).
19    #[error("I/O error")]
20    Io(#[from] std::io::Error),
21
22    /// DOCX package validation or ZIP handling error.
23    #[error("invalid DOCX package: {0}")]
24    Package(#[from] crate::package::PackageError),
25
26    /// XML processing error.
27    #[error("XML processing error: {0}")]
28    Xml(#[from] XmlError),
29
30    /// Template placement or binding error.
31    #[error("template placement error: {0}")]
32    Placement(#[from] crate::domain::binding::BindingError),
33
34    /// Render plan error.
35    #[error("render plan error: {0}")]
36    Plan(#[from] crate::domain::plan::PlanError),
37
38    /// Template rendering error.
39    #[error("template rendering error: {0}")]
40    Render(#[from] crate::domain::engine::RenderError),
41
42    /// Context data error.
43    #[error("invalid template context: {0}")]
44    Context(#[from] crate::context::ContextError),
45}
46
47impl Error {
48    /// Whether this error is a missing template value.
49    ///
50    /// Use it to tell a missing field apart from a malformed template when the
51    /// caller wants to fall back to
52    /// [`MissingValuePolicy::Empty`](crate::MissingValuePolicy).
53    ///
54    /// # Examples
55    ///
56    /// ```
57    /// use docx_templating::{Error, RenderError};
58    ///
59    /// let error = Error::Render(RenderError::MissingValue {
60    ///     path: "user.name".to_owned(),
61    ///     part: Some("word/document.xml".to_owned()),
62    /// });
63    /// assert!(error.is_missing_value());
64    /// ```
65    #[must_use]
66    pub fn is_missing_value(&self) -> bool {
67        matches!(self, Error::Render(RenderError::MissingValue { .. }))
68    }
69}
70
71/// XML error type.
72///
73/// Raised while a DOCX part is parsed into the document model.
74#[derive(Debug, thiserror::Error)]
75#[non_exhaustive]
76pub enum XmlError {
77    /// The part uses an encoding the pipeline does not support.
78    #[error("unsupported encoding in part {part}: {encoding}")]
79    UnsupportedEncoding {
80        /// Part name where error occurred.
81        part: String,
82        /// The detected encoding label.
83        encoding: String,
84    },
85
86    /// The part is not well formed.
87    #[error("malformed XML in part {part}: {message}")]
88    MalformedPart {
89        /// Part name where error occurred.
90        part: String,
91        /// A short description of the problem.
92        message: String,
93    },
94
95    /// The part has no root element.
96    #[error("no root element in part {part}")]
97    NoRoot {
98        /// Part name where error occurred.
99        part: String,
100    },
101
102    /// The part has more than one root element.
103    #[error("multiple root elements in part {part}")]
104    MultipleRoots {
105        /// Part name where error occurred.
106        part: String,
107    },
108}
109
110impl From<crate::adapters::docx::ParseError> for XmlError {
111    fn from(error: crate::adapters::docx::ParseError) -> Self {
112        match error {
113            crate::adapters::docx::ParseError::UnsupportedEncoding { part, encoding } => {
114                XmlError::UnsupportedEncoding { part, encoding }
115            }
116            crate::adapters::docx::ParseError::Malformed { part, message } => {
117                XmlError::MalformedPart { part, message }
118            }
119            crate::adapters::docx::ParseError::NoRoot { part } => XmlError::NoRoot { part },
120            crate::adapters::docx::ParseError::MultipleRoots { part } => {
121                XmlError::MultipleRoots { part }
122            }
123        }
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
130
131    use super::*;
132
133    #[test]
134    fn test_error_display() {
135        let err = Error::Io(std::io::Error::new(
136            std::io::ErrorKind::NotFound,
137            "file not found",
138        ));
139        assert_eq!(err.to_string(), "I/O error");
140    }
141
142    #[test]
143    fn test_result_type_alias() {
144        let result: Result<()> = Ok(());
145        assert!(result.is_ok());
146    }
147}