Skip to main content

odox_core/
error.rs

1//! What can go wrong reading or writing a package.
2//
3// Author: David M. Anderson
4// Built with AI assistance (Claude, Anthropic)
5
6use std::fmt;
7
8/// A package that could not be read, or a document that could not be written.
9#[derive(Debug)]
10pub enum Error {
11    /// The bytes are not a zip archive, or an entry in one could not be read.
12    Package(String),
13    /// An entry the format requires is absent.
14    MissingPart(&'static str),
15    /// The XML in a named part is not well formed.
16    Xml {
17        /// Which entry of the package.
18        part: String,
19        /// What the parser said, with the position it said it at.
20        detail: String,
21    },
22    /// The package is a valid `OpenDocument` package of a kind this application
23    /// does not open. Carries the media type found, so the window can say which
24    /// of its siblings to reach for.
25    WrongFormat {
26        /// The media type the package declares.
27        found: String,
28        /// The media type this reader wanted.
29        wanted: &'static str,
30    },
31    /// The document was serialized and read back, and a part did not come back
32    /// as the tree it was written from. Nothing has been written to disk: this
33    /// is the check that stands between an editor and a document it would have
34    /// damaged.
35    Unfaithful(&'static str),
36}
37
38impl fmt::Display for Error {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            Self::Package(detail) => write!(f, "not a readable package: {detail}"),
42            Self::MissingPart(name) => write!(f, "the package has no {name}"),
43            Self::Xml { part, detail } => write!(f, "{part} is not well-formed XML: {detail}"),
44            Self::WrongFormat { found, wanted } => {
45                write!(f, "this is a {found} package, not a {wanted} one")
46            }
47            Self::Unfaithful(part) => write!(
48                f,
49                "{part} would not read back as it was written, so the document was not saved; please report this"
50            ),
51        }
52    }
53}
54
55impl std::error::Error for Error {}
56
57impl From<zip::result::ZipError> for Error {
58    fn from(e: zip::result::ZipError) -> Self {
59        Self::Package(e.to_string())
60    }
61}