92 lines
2.5 KiB
Rust
Raw Normal View History

2021-09-16 18:31:25 +08:00
use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use futures_channel::mpsc::TrySendError;
use std::fmt::Debug;
use strum_macros::Display;
2021-09-19 18:39:56 +08:00
use tokio_tungstenite::tungstenite::{http::StatusCode, Message};
2021-09-16 18:31:25 +08:00
use url::ParseError;
#[derive(Debug, Default, Clone, ProtoBuf)]
pub struct WsError {
#[pb(index = 1)]
2021-09-23 15:49:10 +08:00
pub code: ErrorCode,
2021-09-16 18:31:25 +08:00
#[pb(index = 2)]
2021-09-23 15:49:10 +08:00
pub msg: String,
2021-09-16 18:31:25 +08:00
}
macro_rules! static_user_error {
($name:ident, $status:expr) => {
#[allow(non_snake_case, missing_docs)]
pub fn $name() -> WsError {
WsError {
code: $status,
msg: format!("{}", $status),
}
}
};
}
impl WsError {
2021-09-17 19:03:46 +08:00
#[allow(dead_code)]
pub(crate) fn new(code: ErrorCode) -> WsError {
WsError {
code,
msg: "".to_string(),
}
}
2021-09-16 18:31:25 +08:00
pub fn context<T: Debug>(mut self, error: T) -> Self {
self.msg = format!("{:?}", error);
self
}
static_user_error!(internal, ErrorCode::InternalError);
2021-09-18 22:32:00 +08:00
static_user_error!(unsupported_message, ErrorCode::UnsupportedMessage);
2021-09-19 18:39:56 +08:00
static_user_error!(unauthorized, ErrorCode::Unauthorized);
2021-09-16 18:31:25 +08:00
}
2021-10-05 17:54:11 +08:00
pub fn internal_error<T>(e: T) -> WsError
where
T: std::fmt::Debug,
{
WsError::internal().context(e)
}
2021-09-16 18:31:25 +08:00
#[derive(Debug, Clone, ProtoBuf_Enum, Display, PartialEq, Eq)]
pub enum ErrorCode {
2021-09-18 22:32:00 +08:00
InternalError = 0,
2021-09-20 15:38:55 +08:00
UnsupportedMessage = 1,
Unauthorized = 2,
2021-09-16 18:31:25 +08:00
}
impl std::default::Default for ErrorCode {
fn default() -> Self { ErrorCode::InternalError }
}
impl std::convert::From<url::ParseError> for WsError {
fn from(error: ParseError) -> Self { WsError::internal().context(error) }
}
2021-09-18 22:32:00 +08:00
impl std::convert::From<protobuf::ProtobufError> for WsError {
fn from(error: protobuf::ProtobufError) -> Self { WsError::internal().context(error) }
}
2021-09-16 18:31:25 +08:00
impl std::convert::From<futures_channel::mpsc::TrySendError<Message>> for WsError {
fn from(error: TrySendError<Message>) -> Self { WsError::internal().context(error) }
}
impl std::convert::From<tokio_tungstenite::tungstenite::Error> for WsError {
2021-09-19 18:39:56 +08:00
fn from(error: tokio_tungstenite::tungstenite::Error) -> Self {
2021-11-27 19:19:41 +08:00
match error {
2021-09-19 18:39:56 +08:00
tokio_tungstenite::tungstenite::Error::Http(response) => {
if response.status() == StatusCode::UNAUTHORIZED {
WsError::unauthorized()
} else {
WsError::internal().context(response)
}
},
_ => WsError::internal().context(error),
2021-11-27 19:19:41 +08:00
}
2021-09-19 18:39:56 +08:00
}
}