use std::fmt;
pub type Result<T, E = KatraError> = core::result::Result<T, E>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorCategory {
InvalidArgument,
NotSupported,
OutOfBudget,
Io,
Protocol,
NotFound,
AlreadyExists,
Corrupt,
Timeout,
Sync,
FallbackUnavailable,
Internal,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KatraError {
InvalidArgument(&'static str),
NotSupported(String),
OutOfBudget {
resource: &'static str,
requested: u64,
available: u64,
},
Io(std::io::ErrorKind, String),
Protocol(String),
NotFound(String),
AlreadyExists(String),
Corrupt(String),
Timeout {
what: &'static str,
timeout_ns: u64,
},
Sync(String),
FallbackUnavailable(&'static str),
Internal(&'static str),
}
impl KatraError {
pub fn category(&self) -> ErrorCategory {
match self {
KatraError::InvalidArgument(_) => ErrorCategory::InvalidArgument,
KatraError::NotSupported(_) => ErrorCategory::NotSupported,
KatraError::OutOfBudget { .. } => ErrorCategory::OutOfBudget,
KatraError::Io(..) => ErrorCategory::Io,
KatraError::Protocol(_) => ErrorCategory::Protocol,
KatraError::NotFound(_) => ErrorCategory::NotFound,
KatraError::AlreadyExists(_) => ErrorCategory::AlreadyExists,
KatraError::Corrupt(_) => ErrorCategory::Corrupt,
KatraError::Timeout { .. } => ErrorCategory::Timeout,
KatraError::Sync(_) => ErrorCategory::Sync,
KatraError::FallbackUnavailable(_) => ErrorCategory::FallbackUnavailable,
KatraError::Internal(_) => ErrorCategory::Internal,
}
}
}
impl fmt::Display for KatraError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
KatraError::InvalidArgument(a) => write!(f, "invalid argument: {a}"),
KatraError::NotSupported(c) => write!(f, "not supported: {c}"),
KatraError::OutOfBudget { resource, requested, available } => write!(
f,
"budget exceeded for {resource}: requested {requested}, available {available}"
),
KatraError::Io(kind, msg) => write!(f, "io error ({kind}): {msg}"),
KatraError::Protocol(msg) => write!(f, "protocol violation: {msg}"),
KatraError::NotFound(msg) => write!(f, "not found: {msg}"),
KatraError::AlreadyExists(msg) => write!(f, "already exists: {msg}"),
KatraError::Corrupt(msg) => write!(f, "corrupt data: {msg}"),
KatraError::Timeout { what, timeout_ns } => {
write!(f, "timeout on {what} after {timeout_ns} ns")
}
KatraError::Sync(msg) => write!(f, "synchronization violation: {msg}"),
KatraError::FallbackUnavailable(s) => write!(f, "fallback unavailable: {s}"),
KatraError::Internal(msg) => write!(f, "internal error: {msg}"),
}
}
}
impl std::error::Error for KatraError {}
impl From<std::io::Error> for KatraError {
fn from(e: std::io::Error) -> Self {
KatraError::Io(e.kind(), e.to_string())
}
}