use thiserror::Error;
#[derive(Error, Debug)]
pub enum WebSocketError {
#[error("Invalid WebSocket upgrade request: {0}")]
InvalidUpgrade(String),
#[error("WebSocket handshake failed: {0}")]
HandshakeFailed(String),
#[error("Connection closed unexpectedly")]
ConnectionClosed,
#[error("Failed to send message: {0}")]
SendFailed(String),
#[error("Failed to receive message: {0}")]
ReceiveFailed(String),
#[error("Message serialization error: {0}")]
SerializationError(String),
#[error("Message deserialization error: {0}")]
DeserializationError(String),
#[error("WebSocket protocol error: {0}")]
ProtocolError(String),
#[error("IO error: {0}")]
IoError(#[from] std::io::Error),
#[error("WebSocket error: {0}")]
Tungstenite(#[from] tungstenite::Error),
}
impl WebSocketError {
pub fn invalid_upgrade(msg: impl Into<String>) -> Self {
Self::InvalidUpgrade(msg.into())
}
pub fn handshake_failed(msg: impl Into<String>) -> Self {
Self::HandshakeFailed(msg.into())
}
pub fn send_failed(msg: impl Into<String>) -> Self {
Self::SendFailed(msg.into())
}
pub fn receive_failed(msg: impl Into<String>) -> Self {
Self::ReceiveFailed(msg.into())
}
pub fn serialization_error(msg: impl Into<String>) -> Self {
Self::SerializationError(msg.into())
}
pub fn deserialization_error(msg: impl Into<String>) -> Self {
Self::DeserializationError(msg.into())
}
pub fn protocol_error(msg: impl Into<String>) -> Self {
Self::ProtocolError(msg.into())
}
}
impl From<WebSocketError> for rustapi_core::ApiError {
fn from(err: WebSocketError) -> Self {
match err {
WebSocketError::InvalidUpgrade(msg) => {
rustapi_core::ApiError::bad_request(format!("WebSocket upgrade failed: {}", msg))
}
WebSocketError::HandshakeFailed(msg) => {
rustapi_core::ApiError::bad_request(format!("WebSocket handshake failed: {}", msg))
}
_ => rustapi_core::ApiError::internal(err.to_string()),
}
}
}
impl From<crate::auth::AuthError> for rustapi_core::ApiError {
fn from(err: crate::auth::AuthError) -> Self {
match err {
crate::auth::AuthError::TokenMissing => {
rustapi_core::ApiError::unauthorized("Authentication token missing")
}
crate::auth::AuthError::TokenExpired => {
rustapi_core::ApiError::unauthorized("Token has expired")
}
crate::auth::AuthError::InvalidSignature => {
rustapi_core::ApiError::unauthorized("Invalid token signature")
}
crate::auth::AuthError::InvalidFormat(msg) => {
rustapi_core::ApiError::bad_request(format!("Invalid token format: {}", msg))
}
crate::auth::AuthError::ValidationFailed(msg) => {
rustapi_core::ApiError::unauthorized(format!("Token validation failed: {}", msg))
}
crate::auth::AuthError::InsufficientPermissions(msg) => {
rustapi_core::ApiError::forbidden(format!("Insufficient permissions: {}", msg))
}
}
}
}