docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
//! Error types for the docx-templating library.
//!
//! This module defines the top-level [`enum@Error`] enum and domain-specific error types.

use crate::domain::engine::RenderError;
use thiserror::Error;

/// Result type alias for docx-templating operations.
pub type Result<T> = std::result::Result<T, Error>;

/// Top-level error type for docx-templating.
///
/// This enum wraps domain-specific errors and provides automatic conversions
/// via `From` implementations powered by `thiserror`.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
    /// I/O error (file operations, ZIP reading/writing).
    #[error("I/O error")]
    Io(#[from] std::io::Error),

    /// DOCX package validation or ZIP handling error.
    #[error("invalid DOCX package: {0}")]
    Package(#[from] crate::package::PackageError),

    /// XML processing error.
    #[error("XML processing error: {0}")]
    Xml(#[from] XmlError),

    /// Template placement or binding error.
    #[error("template placement error: {0}")]
    Placement(#[from] crate::domain::binding::BindingError),

    /// Render plan error.
    #[error("render plan error: {0}")]
    Plan(#[from] crate::domain::plan::PlanError),

    /// Template rendering error.
    #[error("template rendering error: {0}")]
    Render(#[from] crate::domain::engine::RenderError),

    /// Context data error.
    #[error("invalid template context: {0}")]
    Context(#[from] crate::context::ContextError),
}

impl Error {
    /// Whether this error is a missing template value.
    ///
    /// Use it to tell a missing field apart from a malformed template when the
    /// caller wants to fall back to
    /// [`MissingValuePolicy::Empty`](crate::MissingValuePolicy).
    ///
    /// # Examples
    ///
    /// ```
    /// use docx_templating::{Error, RenderError};
    ///
    /// let error = Error::Render(RenderError::MissingValue {
    ///     path: "user.name".to_owned(),
    ///     part: Some("word/document.xml".to_owned()),
    /// });
    /// assert!(error.is_missing_value());
    /// ```
    #[must_use]
    pub fn is_missing_value(&self) -> bool {
        matches!(self, Error::Render(RenderError::MissingValue { .. }))
    }
}

/// XML error type.
///
/// Raised while a DOCX part is parsed into the document model.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum XmlError {
    /// The part uses an encoding the pipeline does not support.
    #[error("unsupported encoding in part {part}: {encoding}")]
    UnsupportedEncoding {
        /// Part name where error occurred.
        part: String,
        /// The detected encoding label.
        encoding: String,
    },

    /// The part is not well formed.
    #[error("malformed XML in part {part}: {message}")]
    MalformedPart {
        /// Part name where error occurred.
        part: String,
        /// A short description of the problem.
        message: String,
    },

    /// The part has no root element.
    #[error("no root element in part {part}")]
    NoRoot {
        /// Part name where error occurred.
        part: String,
    },

    /// The part has more than one root element.
    #[error("multiple root elements in part {part}")]
    MultipleRoots {
        /// Part name where error occurred.
        part: String,
    },
}

impl From<crate::adapters::docx::ParseError> for XmlError {
    fn from(error: crate::adapters::docx::ParseError) -> Self {
        match error {
            crate::adapters::docx::ParseError::UnsupportedEncoding { part, encoding } => {
                XmlError::UnsupportedEncoding { part, encoding }
            }
            crate::adapters::docx::ParseError::Malformed { part, message } => {
                XmlError::MalformedPart { part, message }
            }
            crate::adapters::docx::ParseError::NoRoot { part } => XmlError::NoRoot { part },
            crate::adapters::docx::ParseError::MultipleRoots { part } => {
                XmlError::MultipleRoots { part }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

    use super::*;

    #[test]
    fn test_error_display() {
        let err = Error::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "file not found",
        ));
        assert_eq!(err.to_string(), "I/O error");
    }

    #[test]
    fn test_result_type_alias() {
        let result: Result<()> = Ok(());
        assert!(result.is_ok());
    }
}