#[derive(Debug)]
pub enum WireframeError<E = NoProtocolError> {
DuplicateRoute(u32),
Io(std::io::Error),
Protocol(E),
Codec(crate::codec::CodecError),
}
#[derive(Debug)]
pub struct NoProtocolError;
impl<E> From<E> for WireframeError<E> {
fn from(error: E) -> Self { Self::Protocol(error) }
}
impl<E> WireframeError<E> {
#[must_use]
pub const fn from_io(error: std::io::Error) -> Self { Self::Io(error) }
#[must_use]
pub const fn from_codec(error: crate::codec::CodecError) -> Self { Self::Codec(error) }
#[must_use]
pub const fn is_clean_close(&self) -> bool {
matches!(self, Self::Codec(codec_error) if codec_error.is_clean_close())
}
}
impl<E: std::fmt::Debug> std::fmt::Display for WireframeError<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::DuplicateRoute(id) => write!(f, "route id {id} was already registered"),
Self::Io(error) => write!(f, "transport error: {error}"),
Self::Protocol(error) => write!(f, "protocol error: {error:?}"),
Self::Codec(error) => write!(f, "codec error: {error}"),
}
}
}
fn transport_or_codec_source<E>(
error: &WireframeError<E>,
) -> Option<&(dyn std::error::Error + 'static)> {
match error {
WireframeError::Io(io_error) => Some(io_error),
WireframeError::Codec(codec_error) => Some(codec_error),
WireframeError::DuplicateRoute(_) | WireframeError::Protocol(_) => None,
}
}
impl<E> std::error::Error for WireframeError<E>
where
E: std::fmt::Debug + std::error::Error + 'static,
{
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
transport_or_codec_source(self).or_else(|| protocol_error_source(self))
}
}
impl std::error::Error for WireframeError<NoProtocolError> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
transport_or_codec_source(self)
}
}
fn protocol_error_source<E>(error: &WireframeError<E>) -> Option<&(dyn std::error::Error + 'static)>
where
E: std::error::Error + 'static,
{
match error {
WireframeError::Protocol(protocol_error) => Some(protocol_error),
WireframeError::DuplicateRoute(_) | WireframeError::Io(_) | WireframeError::Codec(_) => {
None
}
}
}
pub type Result<T> = std::result::Result<T, WireframeError>;