use std::fmt;
#[derive(Debug)]
pub enum XlsxError {
Zip(zip::result::ZipError),
MissingPart {
part: String,
},
Xml {
part: String,
source: quick_xml::errors::Error,
},
MissingRelationship {
id: String,
},
CorruptCell {
reference: String,
reason: &'static str,
},
SharedStringRange {
index: u32,
len: usize,
},
NonFiniteNumber(f64),
}
impl fmt::Display for XlsxError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
XlsxError::Zip(e) => write!(f, "zip container error: {e}"),
XlsxError::MissingPart { part } => write!(f, "missing package part: {part}"),
XlsxError::Xml { part, source } => write!(f, "xml parse error in {part}: {source}"),
XlsxError::MissingRelationship { id } => {
write!(f, "workbook sheet references unknown relationship {id:?}")
}
XlsxError::CorruptCell { reference, reason } => {
write!(f, "corrupt cell {reference}: {reason}")
}
XlsxError::SharedStringRange { index, len } => {
write!(
f,
"shared string index {index} out of range (table holds {len})"
)
}
XlsxError::NonFiniteNumber(n) => write!(f, "cannot write non-finite number {n:?}"),
}
}
}
impl std::error::Error for XlsxError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
XlsxError::Zip(e) => Some(e),
XlsxError::Xml { source, .. } => Some(source),
_ => None,
}
}
}
impl From<zip::result::ZipError> for XlsxError {
fn from(e: zip::result::ZipError) -> Self {
XlsxError::Zip(e)
}
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use super::XlsxError;
use std::string::{String, ToString};
#[test]
fn display_is_informative_and_total() {
let cases = [
XlsxError::MissingPart {
part: String::from("xl/workbook.xml"),
},
XlsxError::MissingRelationship {
id: String::from("rId9"),
},
XlsxError::CorruptCell {
reference: String::from("B3"),
reason: "bad number",
},
XlsxError::SharedStringRange { index: 7, len: 2 },
XlsxError::NonFiniteNumber(f64::NAN),
];
for e in cases {
let s = e.to_string();
assert!(!s.is_empty(), "{e:?} rendered empty");
}
let zip_err = zip::result::ZipError::InvalidArchive(std::borrow::Cow::Borrowed("nope"));
let e = XlsxError::Zip(zip_err);
assert!(e.to_string().contains("zip"));
assert!(std::error::Error::source(&e).is_some());
}
}