Skip to main content

einvoice_validator/
error.rs

1//! The errors of loading a rule set and of validating a document.
2
3use std::fmt;
4use std::path::PathBuf;
5
6/// Why a rule set could not be loaded, or a document could not be validated.
7///
8/// Validity problems of a document (schema errors, failed asserts) are not errors: they
9/// are in the [`Report`](crate::Report). An error means that no complete verdict could
10/// be given.
11#[derive(Debug)]
12#[non_exhaustive]
13pub enum Error {
14    /// A file could not be read.
15    Io {
16        /// The file.
17        path: PathBuf,
18        /// The cause.
19        source: std::io::Error,
20    },
21    /// The bundle is not usable: a manifest that does not follow the format, a missing
22    /// file, an unknown schema name, a stylesheet that is not well-formed XSLT, or one
23    /// whose result is not an SVRL report.
24    Bundle {
25        /// What is wrong, naming the file and line when known.
26        message: String,
27    },
28    /// A file of the bundle does not have the SHA-256 its manifest records.
29    Checksum {
30        /// The file, relative to the bundle.
31        path: String,
32        /// The SHA-256 the manifest records (lower-case hexadecimal).
33        expected: String,
34        /// The SHA-256 of the file.
35        actual: String,
36    },
37    /// The document is not well-formed XML (or not UTF-8, or not namespace-well-formed).
38    NotXml {
39        /// 1-based line.
40        line: u32,
41        /// 1-based column.
42        column: u32,
43        /// The parser's message.
44        message: String,
45    },
46    /// The document or a rule-set artefact needs a construct that this engine does not
47    /// implement (an encoding other than UTF-8, a document type declaration, an XSLT or
48    /// XML Schema construct outside the supported subset). Refused rather than answered
49    /// differently from the reference engine.
50    Unsupported {
51        /// What is not supported, and where.
52        message: String,
53    },
54    /// A stylesheet of the rule set raised a dynamic error on the document (the
55    /// reference engine fails on it as well).
56    Transform {
57        /// The stylesheet, by its name in the bundle.
58        stylesheet: String,
59        /// The XPath or XSLT error code (`FORG0001`, ...).
60        code: String,
61        /// The line of the stylesheet instruction, when known.
62        line: Option<u32>,
63        /// The explanation.
64        message: String,
65    },
66    /// A bug of this engine: a result it cannot read back.
67    Internal {
68        /// What went wrong.
69        message: String,
70    },
71}
72
73/// The kind of an [`Error`], for callers that only need to classify it (the exit code of
74/// a command-line tool, ...).
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76#[non_exhaustive]
77pub enum ErrorKind {
78    /// [`Error::Io`].
79    Io,
80    /// [`Error::Bundle`] and [`Error::Checksum`].
81    Bundle,
82    /// [`Error::NotXml`].
83    NotXml,
84    /// [`Error::Unsupported`].
85    Unsupported,
86    /// [`Error::Transform`].
87    Transform,
88    /// [`Error::Internal`].
89    Internal,
90}
91
92impl ErrorKind {
93    /// A stable identifier of the kind: `io`, `bundle`, `not-xml`, `unsupported`,
94    /// `transform` or `internal`.
95    #[must_use]
96    pub const fn as_str(self) -> &'static str {
97        match self {
98            Self::Io => "io",
99            Self::Bundle => "bundle",
100            Self::NotXml => "not-xml",
101            Self::Unsupported => "unsupported",
102            Self::Transform => "transform",
103            Self::Internal => "internal",
104        }
105    }
106}
107
108impl fmt::Display for ErrorKind {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        f.write_str(self.as_str())
111    }
112}
113
114impl Error {
115    /// The kind of the error.
116    #[must_use]
117    pub const fn kind(&self) -> ErrorKind {
118        match self {
119            Self::Io { .. } => ErrorKind::Io,
120            Self::Bundle { .. } | Self::Checksum { .. } => ErrorKind::Bundle,
121            Self::NotXml { .. } => ErrorKind::NotXml,
122            Self::Unsupported { .. } => ErrorKind::Unsupported,
123            Self::Transform { .. } => ErrorKind::Transform,
124            Self::Internal { .. } => ErrorKind::Internal,
125        }
126    }
127
128    pub(crate) fn bundle(message: impl Into<String>) -> Self {
129        Self::Bundle {
130            message: message.into(),
131        }
132    }
133
134    pub(crate) fn unsupported(message: impl Into<String>) -> Self {
135        Self::Unsupported {
136            message: message.into(),
137        }
138    }
139
140    pub(crate) fn internal(message: impl Into<String>) -> Self {
141        Self::Internal {
142            message: message.into(),
143        }
144    }
145}
146
147impl fmt::Display for Error {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        match self {
150            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
151            Self::Bundle { message } => write!(f, "invalid rule-set bundle: {message}"),
152            Self::Checksum {
153                path,
154                expected,
155                actual,
156            } => write!(
157                f,
158                "invalid rule-set bundle: {path}: SHA-256 {actual}, the manifest records {expected}"
159            ),
160            Self::NotXml {
161                line,
162                column,
163                message,
164            } => write!(f, "{line}:{column}: not well-formed XML: {message}"),
165            Self::Unsupported { message } => write!(f, "unsupported: {message}"),
166            Self::Transform {
167                stylesheet,
168                code,
169                line,
170                message,
171            } => {
172                write!(f, "stylesheet {stylesheet}")?;
173                if let Some(line) = line {
174                    write!(f, ", line {line}")?;
175                }
176                write!(f, ": {code}: {message}")
177            }
178            Self::Internal { message } => write!(f, "internal error: {message}"),
179        }
180    }
181}
182
183impl std::error::Error for Error {
184    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
185        match self {
186            Self::Io { source, .. } => Some(source),
187            _ => None,
188        }
189    }
190}