use std::fmt;
use einvoice_xdm::{ErrorCode as XdmCode, XdmError};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
Xpst0008,
Xpst0017,
Xpdy0002,
Xpdy0050,
Xpty0004,
Xpty0018,
Xpty0019,
Xpty0020,
Foar0001,
Foar0002,
Foca0002,
Foch0001,
Fodt0001,
Forg0001,
Forg0006,
Forx0001,
Forx0002,
Forx0003,
Forx0004,
Xtde1360,
Xtde1390,
Host,
Unsupported,
Internal,
}
impl ErrorCode {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Xpst0008 => "XPST0008",
Self::Xpst0017 => "XPST0017",
Self::Xpdy0002 => "XPDY0002",
Self::Xpdy0050 => "XPDY0050",
Self::Xpty0004 => "XPTY0004",
Self::Xpty0018 => "XPTY0018",
Self::Xpty0019 => "XPTY0019",
Self::Xpty0020 => "XPTY0020",
Self::Foar0001 => "FOAR0001",
Self::Foar0002 => "FOAR0002",
Self::Foca0002 => "FOCA0002",
Self::Foch0001 => "FOCH0001",
Self::Fodt0001 => "FODT0001",
Self::Forg0001 => "FORG0001",
Self::Forg0006 => "FORG0006",
Self::Forx0001 => "FORX0001",
Self::Forx0002 => "FORX0002",
Self::Forx0003 => "FORX0003",
Self::Forx0004 => "FORX0004",
Self::Xtde1360 => "XTDE1360",
Self::Xtde1390 => "XTDE1390",
Self::Host => "HOST",
Self::Unsupported => "UNSUPPORTED",
Self::Internal => "INTERNAL",
}
}
#[must_use]
pub const fn is_static(self) -> bool {
matches!(self, Self::Xpst0008 | Self::Xpst0017)
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
code: ErrorCode,
message: String,
}
impl Error {
#[must_use]
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
#[must_use]
pub const fn code(&self) -> ErrorCode {
self.code
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.code, self.message)
}
}
impl std::error::Error for Error {}
impl From<XdmError> for Error {
fn from(e: XdmError) -> Self {
let code = match e.code() {
XdmCode::Foar0001 => ErrorCode::Foar0001,
XdmCode::Foar0002 => ErrorCode::Foar0002,
XdmCode::Foca0002 => ErrorCode::Foca0002,
XdmCode::Fodt0001 => ErrorCode::Fodt0001,
XdmCode::Forg0001 => ErrorCode::Forg0001,
XdmCode::Forg0006 => ErrorCode::Forg0006,
XdmCode::Forx0001 => ErrorCode::Forx0001,
XdmCode::Forx0002 => ErrorCode::Forx0002,
XdmCode::Forx0003 => ErrorCode::Forx0003,
XdmCode::Forx0004 => ErrorCode::Forx0004,
XdmCode::Xpty0004 => ErrorCode::Xpty0004,
_ => ErrorCode::Unsupported,
};
Self::new(code, e.message())
}
}
pub type Result<T> = std::result::Result<T, Error>;
pub(crate) fn err<T>(code: ErrorCode, message: impl Into<String>) -> Result<T> {
Err(Error::new(code, message))
}