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
6use einvoice_xpath_eval::LimitExceeded;
7
8/// Why a rule set could not be loaded, or a document could not be validated.
9///
10/// Validity problems of a document (schema errors, failed asserts) are not errors: they
11/// are in the [`Report`](crate::Report). An error means that no complete verdict could
12/// be given.
13#[derive(Debug)]
14#[non_exhaustive]
15pub enum Error {
16 /// A file could not be read.
17 Io {
18 /// The file.
19 path: PathBuf,
20 /// The cause.
21 source: std::io::Error,
22 },
23 /// The bundle is not usable: a manifest that does not follow the format, a missing
24 /// file, an unknown schema name, a stylesheet that is not well-formed XSLT, or one
25 /// whose result is not an SVRL report.
26 Bundle {
27 /// What is wrong, naming the file and line when known.
28 message: String,
29 },
30 /// A file of the bundle does not have the SHA-256 its manifest records.
31 Checksum {
32 /// The file, relative to the bundle.
33 path: String,
34 /// The SHA-256 the manifest records (lower-case hexadecimal).
35 expected: String,
36 /// The SHA-256 of the file.
37 actual: String,
38 },
39 /// The document is not well-formed XML (or not UTF-8, or not namespace-well-formed).
40 NotXml {
41 /// 1-based line.
42 line: u32,
43 /// 1-based column.
44 column: u32,
45 /// The parser's message.
46 message: String,
47 },
48 /// The document or a rule-set artefact needs a construct that this engine does not
49 /// implement (an encoding other than UTF-8, a document type declaration, an XSLT or
50 /// XML Schema construct outside the supported subset). Refused rather than answered
51 /// differently from the reference engine.
52 Unsupported {
53 /// What is not supported, and where.
54 message: String,
55 },
56 /// The document exceeds a limit that keeps its validation within a bounded call
57 /// stack: an element nested deeper than [`ValidateOptions::max_depth`]
58 /// ([`LimitExceeded::Depth`]), in the document or in a document a stylesheet loads
59 /// with `document()`; or a stylesheet invoking templates and functions one inside
60 /// another beyond the nesting that maximum allows ([`LimitExceeded::Nesting`]).
61 /// Refused rather than risking a stack overflow, which would abort the process.
62 ///
63 /// [`ValidateOptions::max_depth`]: crate::ValidateOptions::max_depth
64 Limit {
65 /// The limit exceeded, with its value and, for a depth, the line and column of
66 /// the element.
67 limit: LimitExceeded,
68 /// Where: the document, or the stylesheet (by its name in the bundle) and the
69 /// line of its instruction.
70 message: String,
71 },
72 /// A stylesheet of the rule set raised a dynamic error on the document (the
73 /// reference engine fails on it as well).
74 Transform {
75 /// The stylesheet, by its name in the bundle.
76 stylesheet: String,
77 /// The XPath or XSLT error code (`FORG0001`, ...).
78 code: String,
79 /// The line of the stylesheet instruction, when known.
80 line: Option<u32>,
81 /// The explanation.
82 message: String,
83 },
84 /// A bug of this engine: a result it cannot read back.
85 Internal {
86 /// What went wrong.
87 message: String,
88 },
89 /// A fetched rule set ([`fetched_rule_sets`](crate::fetched_rule_sets)) that is not
90 /// in the cache: it must be fetched first (`RuleSetCache::fetch`, feature `fetch`;
91 /// `einvoice-validate rules fetch NAME`). Nothing is downloaded without being asked.
92 NotCached {
93 /// The rule set.
94 name: String,
95 /// The cache directory.
96 dir: PathBuf,
97 },
98 /// A rule set could not be fetched: a download failed or did not have its pinned
99 /// digest, an archive is not as published, or its bundle could not be built (no
100 /// Java for the Schematron compiler of Peppol BIS Billing, ...).
101 Fetch {
102 /// What went wrong, naming the URL or file concerned.
103 message: String,
104 },
105 /// No invoice XML could be extracted from a PDF file ([`crate::pdf::extract`]): its
106 /// kind is [`ErrorKind::Unsupported`] for an encrypted file, a PDF feature outside the
107 /// subset read or a limit exceeded, and [`ErrorKind::Io`] otherwise (not a PDF, a
108 /// malformed file, no embedded file with an invoice name or several, XMP metadata
109 /// that is not well-formed): the file cannot be read as an e-invoice.
110 #[cfg(feature = "pdf")]
111 Pdf(einvoice_pdf::Error),
112}
113
114/// The kind of an [`Error`], for callers that only need to classify it (the exit code of
115/// a command-line tool, ...).
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
117#[non_exhaustive]
118pub enum ErrorKind {
119 /// [`Error::Io`] and [`Error::Fetch`], and an `Error::Pdf` (feature `pdf`) for a PDF
120 /// file no invoice can be read from.
121 Io,
122 /// [`Error::Bundle`], [`Error::Checksum`] and [`Error::NotCached`].
123 Bundle,
124 /// [`Error::NotXml`].
125 NotXml,
126 /// [`Error::Unsupported`] and [`Error::Limit`]: input refused rather than
127 /// processed differently from the reference engine, or with an unbounded stack; and
128 /// an `Error::Pdf` (feature `pdf`) for an encrypted PDF file, a PDF feature outside
129 /// the subset read, or a limit of the PDF reader.
130 Unsupported,
131 /// [`Error::Transform`].
132 Transform,
133 /// [`Error::Internal`].
134 Internal,
135}
136
137impl ErrorKind {
138 /// A stable identifier of the kind: `io`, `bundle`, `not-xml`, `unsupported`,
139 /// `transform` or `internal`.
140 #[must_use]
141 pub const fn as_str(self) -> &'static str {
142 match self {
143 Self::Io => "io",
144 Self::Bundle => "bundle",
145 Self::NotXml => "not-xml",
146 Self::Unsupported => "unsupported",
147 Self::Transform => "transform",
148 Self::Internal => "internal",
149 }
150 }
151}
152
153impl fmt::Display for ErrorKind {
154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 f.write_str(self.as_str())
156 }
157}
158
159impl Error {
160 /// The kind of the error.
161 #[must_use]
162 pub const fn kind(&self) -> ErrorKind {
163 match self {
164 Self::Io { .. } | Self::Fetch { .. } => ErrorKind::Io,
165 Self::Bundle { .. } | Self::Checksum { .. } | Self::NotCached { .. } => {
166 ErrorKind::Bundle
167 }
168 Self::NotXml { .. } => ErrorKind::NotXml,
169 Self::Unsupported { .. } | Self::Limit { .. } => ErrorKind::Unsupported,
170 Self::Transform { .. } => ErrorKind::Transform,
171 Self::Internal { .. } => ErrorKind::Internal,
172 #[cfg(feature = "pdf")]
173 Self::Pdf(
174 einvoice_pdf::Error::Encrypted
175 | einvoice_pdf::Error::Unsupported { .. }
176 | einvoice_pdf::Error::LimitExceeded { .. },
177 ) => ErrorKind::Unsupported,
178 #[cfg(feature = "pdf")]
179 Self::Pdf(_) => ErrorKind::Io,
180 }
181 }
182
183 pub(crate) fn bundle(message: impl Into<String>) -> Self {
184 Self::Bundle {
185 message: message.into(),
186 }
187 }
188
189 pub(crate) fn unsupported(message: impl Into<String>) -> Self {
190 Self::Unsupported {
191 message: message.into(),
192 }
193 }
194
195 pub(crate) fn internal(message: impl Into<String>) -> Self {
196 Self::Internal {
197 message: message.into(),
198 }
199 }
200}
201
202impl fmt::Display for Error {
203 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204 match self {
205 Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
206 Self::Bundle { message } => write!(f, "invalid rule-set bundle: {message}"),
207 Self::Checksum {
208 path,
209 expected,
210 actual,
211 } => write!(
212 f,
213 "invalid rule-set bundle: {path}: SHA-256 {actual}, the manifest records {expected}"
214 ),
215 Self::NotXml {
216 line,
217 column,
218 message,
219 } => write!(f, "{line}:{column}: not well-formed XML: {message}"),
220 Self::Unsupported { message } => write!(f, "unsupported: {message}"),
221 Self::Limit { message, .. } => write!(f, "limit exceeded: {message}"),
222 Self::Transform {
223 stylesheet,
224 code,
225 line,
226 message,
227 } => {
228 write!(f, "stylesheet {stylesheet}")?;
229 if let Some(line) = line {
230 write!(f, ", line {line}")?;
231 }
232 write!(f, ": {code}: {message}")
233 }
234 Self::Internal { message } => write!(f, "internal error: {message}"),
235 Self::NotCached { name, dir } => write!(
236 f,
237 "rule set {name} is not in the cache ({}): it must be fetched first",
238 dir.display()
239 ),
240 Self::Fetch { message } => write!(f, "cannot fetch the rule set: {message}"),
241 #[cfg(feature = "pdf")]
242 Self::Pdf(error) => error.fmt(f),
243 }
244 }
245}
246
247impl std::error::Error for Error {
248 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
249 match self {
250 Self::Io { source, .. } => Some(source),
251 #[cfg(feature = "pdf")]
252 Self::Pdf(error) => Some(error),
253 _ => None,
254 }
255 }
256}