errors.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
  2. use futures_channel::mpsc::TrySendError;
  3. use std::fmt::Debug;
  4. use strum_macros::Display;
  5. use tokio_tungstenite::tungstenite::{http::StatusCode, Message};
  6. use url::ParseError;
  7. #[derive(Debug, Default, Clone, ProtoBuf)]
  8. pub struct WsError {
  9. #[pb(index = 1)]
  10. pub code: ErrorCode,
  11. #[pb(index = 2)]
  12. pub msg: String,
  13. }
  14. macro_rules! static_user_error {
  15. ($name:ident, $status:expr) => {
  16. #[allow(non_snake_case, missing_docs)]
  17. pub fn $name() -> WsError {
  18. WsError {
  19. code: $status,
  20. msg: format!("{}", $status),
  21. }
  22. }
  23. };
  24. }
  25. impl WsError {
  26. #[allow(dead_code)]
  27. pub(crate) fn new(code: ErrorCode) -> WsError {
  28. WsError {
  29. code,
  30. msg: "".to_string(),
  31. }
  32. }
  33. pub fn context<T: Debug>(mut self, error: T) -> Self {
  34. self.msg = format!("{:?}", error);
  35. self
  36. }
  37. static_user_error!(internal, ErrorCode::InternalError);
  38. static_user_error!(unsupported_message, ErrorCode::UnsupportedMessage);
  39. static_user_error!(unauthorized, ErrorCode::Unauthorized);
  40. }
  41. pub fn internal_error<T>(e: T) -> WsError
  42. where
  43. T: std::fmt::Debug,
  44. {
  45. WsError::internal().context(e)
  46. }
  47. #[derive(Debug, Clone, ProtoBuf_Enum, Display, PartialEq, Eq)]
  48. pub enum ErrorCode {
  49. InternalError = 0,
  50. UnsupportedMessage = 1,
  51. Unauthorized = 2,
  52. }
  53. impl std::default::Default for ErrorCode {
  54. fn default() -> Self { ErrorCode::InternalError }
  55. }
  56. impl std::convert::From<url::ParseError> for WsError {
  57. fn from(error: ParseError) -> Self { WsError::internal().context(error) }
  58. }
  59. impl std::convert::From<protobuf::ProtobufError> for WsError {
  60. fn from(error: protobuf::ProtobufError) -> Self { WsError::internal().context(error) }
  61. }
  62. impl std::convert::From<futures_channel::mpsc::TrySendError<Message>> for WsError {
  63. fn from(error: TrySendError<Message>) -> Self { WsError::internal().context(error) }
  64. }
  65. impl std::convert::From<tokio_tungstenite::tungstenite::Error> for WsError {
  66. fn from(error: tokio_tungstenite::tungstenite::Error) -> Self {
  67. let error = match error {
  68. tokio_tungstenite::tungstenite::Error::Http(response) => {
  69. if response.status() == StatusCode::UNAUTHORIZED {
  70. WsError::unauthorized()
  71. } else {
  72. WsError::internal().context(response)
  73. }
  74. },
  75. _ => WsError::internal().context(error),
  76. };
  77. error
  78. }
  79. }