use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TransportErrorKind {
Connect,
Protocol,
Http { status: u16 },
Closed,
Other,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransportError {
pub kind: TransportErrorKind,
pub message: String,
}
impl TransportError {
pub fn new(kind: TransportErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
}
}
pub fn connect(message: impl Into<String>) -> Self {
Self::new(TransportErrorKind::Connect, message)
}
pub fn protocol(message: impl Into<String>) -> Self {
Self::new(TransportErrorKind::Protocol, message)
}
pub fn http(status: u16, message: impl Into<String>) -> Self {
Self::new(TransportErrorKind::Http { status }, message)
}
pub fn closed(message: impl Into<String>) -> Self {
Self::new(TransportErrorKind::Closed, message)
}
pub fn other(message: impl Into<String>) -> Self {
Self::new(TransportErrorKind::Other, message)
}
}
impl fmt::Display for TransportError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind {
TransportErrorKind::Connect => write!(f, "transport connect: {}", self.message),
TransportErrorKind::Protocol => write!(f, "transport protocol: {}", self.message),
TransportErrorKind::Http { status } => {
write!(f, "transport http {}: {}", status, self.message)
}
TransportErrorKind::Closed => write!(f, "transport closed: {}", self.message),
TransportErrorKind::Other => write!(f, "transport: {}", self.message),
}
}
}
impl std::error::Error for TransportError {}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ClientError {
Transport(TransportError),
Remote {
message: String,
code: Option<String>,
recoverable: bool,
},
Decode {
content_type: Option<String>,
message: String,
},
Encode {
param: &'static str,
message: String,
},
}
impl ClientError {
pub fn is_transport(&self) -> bool {
matches!(self, ClientError::Transport(_))
}
pub fn is_remote(&self) -> bool {
matches!(self, ClientError::Remote { .. })
}
}
impl From<TransportError> for ClientError {
fn from(e: TransportError) -> Self {
ClientError::Transport(e)
}
}
impl fmt::Display for ClientError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ClientError::Transport(e) => write!(f, "{e}"),
ClientError::Remote {
message,
code: Some(code),
..
} => write!(f, "remote error [{code}]: {message}"),
ClientError::Remote { message, .. } => write!(f, "remote error: {message}"),
ClientError::Decode {
content_type: Some(ct),
message,
} => write!(f, "decode {ct}: {message}"),
ClientError::Decode { message, .. } => write!(f, "decode: {message}"),
ClientError::Encode { param, message } => {
write!(f, "encode param `{param}`: {message}")
}
}
}
}
impl std::error::Error for ClientError {}