laravel-template-engine 0.2.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! The package's errors.

use std::error::Error;
use std::fmt;

use laravel::errors::Status;

use crate::Issue;

/// Something the template engine can't do.
#[derive(Debug, Clone, PartialEq, Eq, Status)]
#[status(422)]
#[non_exhaustive]
pub enum TemplateError {
    /// The template has mistakes; each issue says where and what.
    Invalid(Vec<Issue>),
    /// No template type has this key.
    UnknownType(String),
    /// The template isn't in the table.
    NotFound(i64),
    /// A document was asked for, but the type has no active document template, or several and
    /// none was chosen with `named` or `template`.
    NoDocument {
        /// The template type.
        type_key: String,
        /// How many active document templates the type has.
        found: usize,
    },
    /// The template didn't render, for example because it ran past a limit.
    Render(String),
    /// A PDF was asked for, but the crate's `pdf` feature is off.
    PdfDisabled,
}

impl TemplateError {
    /// The issues of an [`TemplateError::Invalid`] error, for an editor to show next to the fields.
    #[must_use]
    pub fn issues(&self) -> &[Issue] {
        match self {
            Self::Invalid(issues) => issues,
            _ => &[],
        }
    }
}

impl fmt::Display for TemplateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Invalid(issues) => {
                f.write_str("The template has mistakes:")?;
                for issue in issues {
                    write!(f, "\n- {issue}")?;
                }
                Ok(())
            }
            Self::UnknownType(key) => write!(f, "There's no template type `{key}`."),
            Self::NotFound(id) => write!(f, "The template `{id}` doesn't exist."),
            Self::NoDocument { type_key, found: 0 } => {
                write!(f, "`{type_key}` has no active document template.")
            }
            Self::NoDocument { type_key, found } => write!(
                f,
                "`{type_key}` has {found} active document templates; choose one with `named` or `template`."
            ),
            Self::Render(message) => write!(f, "The template didn't render: {message}"),
            Self::PdfDisabled => f.write_str("PDF documents need the `pdf` feature of laravel-template-engine."),
        }
    }
}

impl Error for TemplateError {}