errors.rs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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_ws_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_ws_error!(internal, ErrorCode::InternalError);
  38. static_ws_error!(unsupported_message, ErrorCode::UnsupportedMessage);
  39. static_ws_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. 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. }
  78. }