Skip to main content

laravel_template_engine/
error.rs

1//! The package's errors.
2
3use std::error::Error;
4use std::fmt;
5
6use laravel::errors::Status;
7
8use crate::Issue;
9
10/// Something the template engine can't do.
11#[derive(Debug, Clone, PartialEq, Eq, Status)]
12#[status(422)]
13#[non_exhaustive]
14pub enum TemplateError {
15    /// The template has mistakes; each issue says where and what.
16    Invalid(Vec<Issue>),
17    /// No template type has this key.
18    UnknownType(String),
19    /// The template isn't in the table.
20    NotFound(i64),
21    /// A document was asked for, but the type has no active document template, or several and
22    /// none was chosen with `named` or `template`.
23    NoDocument {
24        /// The template type.
25        type_key: String,
26        /// How many active document templates the type has.
27        found: usize,
28    },
29    /// The template didn't render, for example because it ran past a limit.
30    Render(String),
31    /// A PDF was asked for, but the crate's `pdf` feature is off.
32    PdfDisabled,
33    /// A notification asked for a channel no active template of its type writes for.
34    NoNotification {
35        /// The template type.
36        type_key: String,
37        /// The channel.
38        channel: String,
39    },
40}
41
42impl TemplateError {
43    /// The issues of an [`TemplateError::Invalid`] error, for an editor to show next to the fields.
44    #[must_use]
45    pub fn issues(&self) -> &[Issue] {
46        match self {
47            Self::Invalid(issues) => issues,
48            _ => &[],
49        }
50    }
51}
52
53impl fmt::Display for TemplateError {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self {
56            Self::Invalid(issues) => {
57                f.write_str("The template has mistakes:")?;
58                for issue in issues {
59                    write!(f, "\n- {issue}")?;
60                }
61                Ok(())
62            }
63            Self::UnknownType(key) => write!(f, "There's no template type `{key}`."),
64            Self::NotFound(id) => write!(f, "The template `{id}` doesn't exist."),
65            Self::NoDocument { type_key, found: 0 } => {
66                write!(f, "`{type_key}` has no active document template.")
67            }
68            Self::NoDocument { type_key, found } => write!(
69                f,
70                "`{type_key}` has {found} active document templates; choose one with `named` or `template`."
71            ),
72            Self::Render(message) => write!(f, "The template didn't render: {message}"),
73            Self::PdfDisabled => f.write_str("PDF documents need the `pdf` feature of laravel-template-engine."),
74            Self::NoNotification { type_key, channel } => {
75                write!(f, "`{type_key}` has no active notification template for `{channel}`.")
76            }
77        }
78    }
79}
80
81impl Error for TemplateError {}