lib_epub/
error.rs

1//! Error Type Definition Module
2//!
3//! This module defines the various error types that may be encountered during
4//! EPUB file parsing and processing. All errors are uniformly wrapped in the
5//! `EpubError` enumeration for convenient error handling by the caller.
6//!
7//! ## Main Error Types
8//!
9//! - [EpubError] - Enumeration of main errors during EPUB processing
10//! - [EpubBuilderError] - Specific errors during EPUB build process (requires `builder` functionality enabled)
11
12use thiserror::Error;
13
14/// Types of errors that can occur during EPUB processing
15///
16/// This enumeration defines the various error cases that can be encountered
17/// when parsing and processing EPUB files, including file format errors,
18/// missing resources, compression issues, etc.
19#[derive(Debug, Error)]
20pub enum EpubError {
21    /// ZIP archive related errors
22    ///
23    /// Errors occur when processing the ZIP structure of EPUB files,
24    /// such as file corruption, unreadability, etc.
25    #[error("Archive error: {source}")]
26    ArchiveError { source: zip::result::ZipError },
27
28    /// Data Decoding Error - Null dataw
29    ///
30    /// This error occurs when trying to decode an empty stream.
31    #[error("Decode error: The data is empty.")]
32    EmptyDataError,
33
34    #[cfg(feature = "builder")]
35    #[error("Epub builder error: {source}")]
36    EpubBuilderError { source: EpubBuilderError },
37
38    /// XML parsing failure error
39    ///
40    /// This error usually only occurs when there is an exception in the XML parsing process,
41    /// the event listener ends abnormally, resulting in the root node not being initialized.
42    /// This exception may be caused by an incorrect XML file.
43    #[error(
44        "Failed parsing XML error: Unknown problems occurred during XML parsing, causing parsing failure."
45    )]
46    FailedParsingXml,
47
48    #[error("IO error: {source}")]
49    IOError { source: std::io::Error },
50
51    /// Missing required attribute error
52    ///
53    /// Triggered when an XML element in an EPUB file lacks the required
54    /// attributes required by the EPUB specification.
55    #[error(
56        "Missing required attribute: The \"{attribute}\" attribute is a must attribute for the \"{tag}\" element."
57    )]
58    MissingRequiredAttribute { tag: String, attribute: String },
59
60    /// Non-canonical EPUB structure error
61    ///
62    /// This error occurs when an EPUB file lacks some files or directory
63    /// structure that is required in EPUB specification.
64    #[error("Non-canonical epub: The \"{expected_file}\" file was not found.")]
65    NonCanonicalEpub { expected_file: String },
66
67    /// Non-canonical file structure error
68    ///
69    /// This error is triggered when the required XML elements in the
70    /// specification are missing from the EPUB file.
71    #[error("Non-canonical file: The \"{tag}\" elements was not found.")]
72    NonCanonicalFile { tag: String },
73
74    /// Missing supported file format error
75    ///
76    /// This error occurs when trying to get a resource but there isn't any supported file format.
77    /// It usually happens when there are no supported formats available in the fallback chain.
78    #[error(
79        "No supported file format: The fallback resource does not contain the file format you support."
80    )]
81    NoSupportedFileFormat,
82
83    /// Relative link leak error
84    ///
85    /// This error occurs when a relative path link is outside the scope
86    /// of an EPUB container, which is a security protection mechanism.
87    #[error("Relative link leakage: Path \"{path}\" is out of container range.")]
88    RealtiveLinkLeakage { path: String },
89
90    /// Unable to find the resource id error
91    ///
92    /// This error occurs when trying to get a resource by id but that id doesn't exist in the manifest.
93    #[error("Resource Id Not Exist: There is no resource item with id \"{id}\".")]
94    ResourceIdNotExist { id: String },
95
96    /// Unable to find the resource error
97    ///
98    /// This error occurs when an attempt is made to get a resource
99    /// but it does not exist in the EPUB container.
100    #[error("Resource not found: Unable to find resource from \"{resource}\".")]
101    ResourceNotFound { resource: String },
102
103    /// Unrecognized EPUB version error
104    ///
105    /// This error occurs when parsing epub files, the library cannot
106    /// directly or indirectly identify the epub version number.
107    #[error(
108        "Unrecognized EPUB version: Unable to identify version number and version characteristics from epub file"
109    )]
110    UnrecognizedEpubVersion,
111
112    /// Unsupported encryption method error
113    ///
114    /// This error is triggered when attempting to decrypt a resource that uses
115    /// an encryption method not supported by this library.
116    ///
117    /// Currently, this library only supports:
118    /// - IDPF Font Obfuscation
119    /// - Adobe Font Obfuscation
120    #[error("Unsupported encryption method: The \"{method}\" encryption method is not supported.")]
121    UnsupportedEncryptedMethod { method: String },
122
123    /// Unusable compression method error
124    ///
125    /// This error occurs when an EPUB file uses an unsupported compression method.
126    #[error(
127        "Unusable compression method: The \"{file}\" file uses the unsupported \"{method}\" compression method."
128    )]
129    UnusableCompressionMethod { file: String, method: String },
130
131    /// UTF-8 decoding error
132    ///
133    /// This error occurs when attempting to decode byte data into a UTF-8 string
134    /// but the data is not formatted correctly.
135    #[error("Decode error: {source}")]
136    Utf8DecodeError { source: std::string::FromUtf8Error },
137
138    /// UTF-16 decoding error
139    ///
140    /// This error occurs when attempting to decode byte data into a UTF-16 string
141    /// but the data is not formatted correctly.
142    #[error("Decode error: {source}")]
143    Utf16DecodeError { source: std::string::FromUtf16Error },
144
145    /// WalkDir error
146    /// 
147    /// This error occurs when using the WalkDir library to traverse the directory.
148    #[cfg(feature = "builder")]
149    #[error("WalkDir error: {source}")]
150    WalkDirError { source: walkdir::Error },
151
152    /// QuickXml error
153    ///
154    /// This error occurs when parsing XML data using the QuickXml library.
155    #[error("QuickXml error: {source}")]
156    QuickXmlError { source: quick_xml::Error },
157}
158
159impl From<zip::result::ZipError> for EpubError {
160    fn from(value: zip::result::ZipError) -> Self {
161        EpubError::ArchiveError { source: value }
162    }
163}
164
165impl From<quick_xml::Error> for EpubError {
166    fn from(value: quick_xml::Error) -> Self {
167        EpubError::QuickXmlError { source: value }
168    }
169}
170
171impl From<std::io::Error> for EpubError {
172    fn from(value: std::io::Error) -> Self {
173        EpubError::IOError { source: value }
174    }
175}
176
177impl From<std::string::FromUtf8Error> for EpubError {
178    fn from(value: std::string::FromUtf8Error) -> Self {
179        EpubError::Utf8DecodeError { source: value }
180    }
181}
182
183impl From<std::string::FromUtf16Error> for EpubError {
184    fn from(value: std::string::FromUtf16Error) -> Self {
185        EpubError::Utf16DecodeError { source: value }
186    }
187}
188
189#[cfg(feature = "builder")]
190impl From<EpubBuilderError> for EpubError {
191    fn from(value: EpubBuilderError) -> Self {
192        EpubError::EpubBuilderError { source: value }
193    }
194}
195
196#[cfg(feature = "builder")]
197impl From<walkdir::Error> for EpubError {
198    fn from(value: walkdir::Error) -> Self {
199        EpubError::WalkDirError { source: value }
200    }
201}
202
203#[cfg(test)]
204impl PartialEq for EpubError {
205    fn eq(&self, other: &Self) -> bool {
206        match (self, other) {
207            (
208                Self::MissingRequiredAttribute {
209                    tag: l_tag,
210                    attribute: l_attribute,
211                },
212                Self::MissingRequiredAttribute {
213                    tag: r_tag,
214                    attribute: r_attribute,
215                },
216            ) => l_tag == r_tag && l_attribute == r_attribute,
217            (
218                Self::NonCanonicalEpub {
219                    expected_file: l_expected_file,
220                },
221                Self::NonCanonicalEpub {
222                    expected_file: r_expected_file,
223                },
224            ) => l_expected_file == r_expected_file,
225            (Self::NonCanonicalFile { tag: l_tag }, Self::NonCanonicalFile { tag: r_tag }) => {
226                l_tag == r_tag
227            }
228            (
229                Self::RealtiveLinkLeakage { path: l_path },
230                Self::RealtiveLinkLeakage { path: r_path },
231            ) => l_path == r_path,
232            (Self::ResourceIdNotExist { id: l_id }, Self::ResourceIdNotExist { id: r_id }) => {
233                l_id == r_id
234            }
235            (
236                Self::ResourceNotFound {
237                    resource: l_resource,
238                },
239                Self::ResourceNotFound {
240                    resource: r_resource,
241                },
242            ) => l_resource == r_resource,
243            (
244                Self::UnsupportedEncryptedMethod { method: l_method },
245                Self::UnsupportedEncryptedMethod { method: r_method },
246            ) => l_method == r_method,
247            (
248                Self::UnusableCompressionMethod {
249                    file: l_file,
250                    method: l_method,
251                },
252                Self::UnusableCompressionMethod {
253                    file: r_file,
254                    method: r_method,
255                },
256            ) => l_file == r_file && l_method == r_method,
257            (
258                Self::Utf8DecodeError { source: l_source },
259                Self::Utf8DecodeError { source: r_source },
260            ) => l_source == r_source,
261
262            (
263                Self::EpubBuilderError { source: l_source },
264                Self::EpubBuilderError { source: r_source },
265            ) => l_source == r_source,
266
267            _ => core::mem::discriminant(self) == core::mem::discriminant(other),
268        }
269    }
270}
271
272/// Types of errors that can occur during EPUB build
273///
274/// This enumeration defines various error conditions that may occur
275/// when creating EPUB files using the `builder` function. These errors
276/// are typically related to EPUB specification requirements or validation
277/// rules during the build process.
278#[cfg(feature = "builder")]
279#[derive(Debug, Error)]
280#[cfg_attr(test, derive(PartialEq))]
281pub enum EpubBuilderError {
282    /// Illegal manifest path error
283    ///
284    /// This error is triggered when the path corresponding to a resource ID
285    /// in the manifest begins with "../". Using relative paths starting with "../"
286    /// when building the manifest fails to determine the 'current location',
287    /// making it impossible to pinpoint the resource.
288    #[error(
289        "A manifest with id '{manifest_id}' should not use a relative path starting with '../'."
290    )]
291    IllegalManifestPath { manifest_id: String },
292
293    /// Invalid rootfile path error
294    ///
295    /// This error is triggered when the rootfile path in the container.xml is invalid.
296    /// According to the EPUB specification, rootfile paths must be relative paths
297    /// that do not start with "../" to prevent directory traversal outside the EPUB container.
298    #[error("A rootfile path should be a relative path and not start with '../'.")]
299    IllegalRootfilePath,
300
301    /// Manifest Circular Reference error
302    ///
303    /// This error is triggered when a fallback relationship between manifest items forms a cycle.
304    #[error("Circular reference detected in fallback chain for '{fallback_chain}'.")]
305    ManifestCircularReference { fallback_chain: String },
306
307    /// Manifest resource not found error
308    ///
309    /// This error is triggered when a manifest item specifies a fallback resource ID that does not exist.
310    #[error("Fallback resource '{manifest_id}' does not exist in manifest.")]
311    ManifestNotFound { manifest_id: String },
312
313    /// Missing necessary metadata error
314    ///
315    /// This error is triggered when the basic metadata required to build a valid EPUB is missing.
316    /// The following must be included: title, language, and an identifier with a 'pub-id' ID.
317    #[error("Requires at least one 'title', 'language', and 'identifier' with id 'pub-id'.")]
318    MissingNecessaryMetadata,
319
320    /// Navigation information uninitialized error
321    ///
322    /// This error is triggered when attempting to build an EPUB but without setting navigation information.
323    #[error("Navigation information is not set.")]
324    NavigationInfoUninitalized,
325
326    /// Missing rootfile error
327    ///
328    /// This error is triggered when attempting to build an EPUB without adding any 'rootfile'.
329    #[error("Need at least one rootfile.")]
330    MissingRootfile,
331
332    /// Target is not a file error
333    ///
334    /// This error is triggered when the specified target path is not a file.
335    #[error("Expect a file, but '{target_path}' is not a file.")]
336    TargetIsNotFile { target_path: String },
337
338    /// Too many nav flags error
339    ///
340    /// This error is triggered when the manifest contains multiple items with
341    /// the `nav` attribute. The EPUB specification requires that each EPUB have
342    /// **only one** navigation document.
343    #[error("There are too many items with 'nav' property in the manifest.")]
344    TooManyNavFlags,
345
346    /// Unknown file format error
347    ///
348    /// This error is triggered when the format type of the specified file cannot be analyzed.
349    #[error("Unable to analyze the file '{file_path}' type.")]
350    UnknownFileFormat { file_path: String },
351}