pub struct Error {
inner: ErrorKind,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.inner {
ErrorKind::SerializeError(msg) => write!(f, "Serialize error: {}", msg),
ErrorKind::DeserializeError(msg) => write!(f, "Deserialize error: {}", msg),
ErrorKind::ValidateError(code, msg) => {
write!(f, "Validation error: code {} is invalid: {}", code, msg)
}
}
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.inner {
ErrorKind::SerializeError(msg) => write!(f, "Serialize error: {}", msg),
ErrorKind::DeserializeError(msg) => write!(f, "Deserialize error: {}", msg),
ErrorKind::ValidateError(code, msg) => {
write!(f, "Validation error: code {} is invalid: {}", code, msg)
}
}
}
}
impl std::error::Error for Error {}
impl Error {
pub fn serialize(msg: String) -> Self {
Error {
inner: ErrorKind::SerializeError(msg),
}
}
pub fn deserialize(msg: String) -> Self {
Error {
inner: ErrorKind::DeserializeError(msg),
}
}
pub fn validate(value: i64, msg: String) -> Self {
Error {
inner: ErrorKind::ValidateError(value, msg),
}
}
pub fn kind(&self) -> &ErrorKind {
&self.inner
}
}
pub enum ErrorKind {
SerializeError(String),
DeserializeError(String),
ValidateError(i64, String),
}
impl ErrorKind {
pub fn message(&self) -> &str {
match self {
ErrorKind::SerializeError(msg) => msg,
ErrorKind::DeserializeError(msg) => msg,
ErrorKind::ValidateError(_, msg) => msg,
}
}
pub fn code(&self) -> Option<i64> {
match self {
ErrorKind::ValidateError(code, _) => Some(*code),
_ => None,
}
}
}
pub struct ValidateError {
code: i64,
message: String,
}
impl std::fmt::Display for ValidateError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Validation error: code {}, message {}",
self.code, self.message
)
}
}
impl std::fmt::Debug for ValidateError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Validation error: code {}, message {}",
self.code, self.message
)
}
}
impl std::error::Error for ValidateError {}
impl ValidateError {
pub fn new(code: i64, message: String) -> Self {
ValidateError { code, message }
}
pub fn to_afastdata_error(&self) -> Error {
Error::validate(self.code, self.message.clone())
}
}