use std::fmt;
use std::path::PathBuf;
use einvoice_xpath_eval::LimitExceeded;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Io {
path: PathBuf,
source: std::io::Error,
},
Bundle {
message: String,
},
Checksum {
path: String,
expected: String,
actual: String,
},
NotXml {
line: u32,
column: u32,
message: String,
},
Unsupported {
message: String,
},
Limit {
limit: LimitExceeded,
message: String,
},
Transform {
stylesheet: String,
code: String,
line: Option<u32>,
message: String,
},
Internal {
message: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
Io,
Bundle,
NotXml,
Unsupported,
Transform,
Internal,
}
impl ErrorKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Io => "io",
Self::Bundle => "bundle",
Self::NotXml => "not-xml",
Self::Unsupported => "unsupported",
Self::Transform => "transform",
Self::Internal => "internal",
}
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl Error {
#[must_use]
pub const fn kind(&self) -> ErrorKind {
match self {
Self::Io { .. } => ErrorKind::Io,
Self::Bundle { .. } | Self::Checksum { .. } => ErrorKind::Bundle,
Self::NotXml { .. } => ErrorKind::NotXml,
Self::Unsupported { .. } | Self::Limit { .. } => ErrorKind::Unsupported,
Self::Transform { .. } => ErrorKind::Transform,
Self::Internal { .. } => ErrorKind::Internal,
}
}
pub(crate) fn bundle(message: impl Into<String>) -> Self {
Self::Bundle {
message: message.into(),
}
}
pub(crate) fn unsupported(message: impl Into<String>) -> Self {
Self::Unsupported {
message: message.into(),
}
}
pub(crate) fn internal(message: impl Into<String>) -> Self {
Self::Internal {
message: message.into(),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
Self::Bundle { message } => write!(f, "invalid rule-set bundle: {message}"),
Self::Checksum {
path,
expected,
actual,
} => write!(
f,
"invalid rule-set bundle: {path}: SHA-256 {actual}, the manifest records {expected}"
),
Self::NotXml {
line,
column,
message,
} => write!(f, "{line}:{column}: not well-formed XML: {message}"),
Self::Unsupported { message } => write!(f, "unsupported: {message}"),
Self::Limit { message, .. } => write!(f, "limit exceeded: {message}"),
Self::Transform {
stylesheet,
code,
line,
message,
} => {
write!(f, "stylesheet {stylesheet}")?;
if let Some(line) = line {
write!(f, ", line {line}")?;
}
write!(f, ": {code}: {message}")
}
Self::Internal { message } => write!(f, "internal error: {message}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
_ => None,
}
}
}