errors.rs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. use std::fmt;
  2. use std::fmt::Debug;
  3. use strum_macros::Display;
  4. macro_rules! static_error {
  5. ($name:ident, $status:expr) => {
  6. #[allow(non_snake_case, missing_docs)]
  7. pub fn $name() -> SyncError {
  8. SyncError {
  9. code: $status,
  10. msg: format!("{}", $status),
  11. }
  12. }
  13. };
  14. }
  15. pub type SyncResult<T> = std::result::Result<T, SyncError>;
  16. #[derive(Debug, Clone)]
  17. pub struct SyncError {
  18. pub code: ErrorCode,
  19. pub msg: String,
  20. }
  21. impl SyncError {
  22. fn new(code: ErrorCode, msg: &str) -> Self {
  23. Self {
  24. code,
  25. msg: msg.to_owned(),
  26. }
  27. }
  28. pub fn context<T: Debug>(mut self, error: T) -> Self {
  29. self.msg = format!("{:?}", error);
  30. self
  31. }
  32. static_error!(serde, ErrorCode::SerdeError);
  33. static_error!(internal, ErrorCode::InternalError);
  34. static_error!(undo, ErrorCode::UndoFail);
  35. static_error!(redo, ErrorCode::RedoFail);
  36. static_error!(out_of_bound, ErrorCode::OutOfBound);
  37. static_error!(record_not_found, ErrorCode::RecordNotFound);
  38. static_error!(revision_conflict, ErrorCode::RevisionConflict);
  39. static_error!(
  40. can_not_delete_primary_field,
  41. ErrorCode::CannotDeleteThePrimaryField
  42. );
  43. static_error!(
  44. unexpected_empty_revision,
  45. ErrorCode::UnexpectedEmptyRevision
  46. );
  47. }
  48. impl fmt::Display for SyncError {
  49. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  50. write!(f, "{:?}: {}", &self.code, &self.msg)
  51. }
  52. }
  53. #[derive(Debug, Clone, Display, PartialEq, Eq)]
  54. pub enum ErrorCode {
  55. DocumentIdInvalid = 0,
  56. DocumentNotfound = 1,
  57. UndoFail = 2,
  58. RedoFail = 3,
  59. OutOfBound = 4,
  60. RevisionConflict = 5,
  61. RecordNotFound = 6,
  62. CannotDeleteThePrimaryField = 7,
  63. UnexpectedEmptyRevision = 8,
  64. SerdeError = 100,
  65. InternalError = 101,
  66. }
  67. impl std::convert::From<lib_ot::errors::OTError> for SyncError {
  68. fn from(error: lib_ot::errors::OTError) -> Self {
  69. SyncError::new(ErrorCode::InternalError, "").context(error)
  70. }
  71. }
  72. // impl std::convert::From<protobuf::ProtobufError> for SyncError {
  73. // fn from(e: protobuf::ProtobufError) -> Self {
  74. // SyncError::internal().context(e)
  75. // }
  76. // }
  77. pub fn internal_sync_error<T>(e: T) -> SyncError
  78. where
  79. T: std::fmt::Debug,
  80. {
  81. SyncError::internal().context(e)
  82. }