use std::{fmt, io};
pub type WebSocketResult<T> = Result<T, WebSocketError>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WebSocketCloseFrame {
pub code: u16,
pub reason: String,
}
impl WebSocketCloseFrame {
pub fn new(code: u16, reason: impl Into<String>) -> Self {
Self {
code,
reason: reason.into(),
}
}
}
#[derive(Debug)]
pub enum WebSocketError {
Transport(io::Error),
Protocol(String),
MessageTooLarge {
len: usize,
limit: usize,
},
}
impl From<io::Error> for WebSocketError {
fn from(error: io::Error) -> Self {
Self::Transport(error)
}
}
impl fmt::Display for WebSocketError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Transport(err) => write!(f, "transport error: {err}"),
Self::Protocol(err) => write!(f, "protocol error: {err}"),
Self::MessageTooLarge { len, limit } => write!(
f,
"message of {len} bytes exceeds the configured maximum of {limit} bytes"
),
}
}
}
impl std::error::Error for WebSocketError {}
#[cfg(feature = "json")]
impl From<serde_json::Error> for WebSocketError {
fn from(error: serde_json::Error) -> Self {
Self::Protocol(error.to_string())
}
}