errors.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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!(can_not_delete_primary_field, ErrorCode::CannotDeleteThePrimaryField);
  40. static_error!(unexpected_empty_revision, ErrorCode::UnexpectedEmptyRevision);
  41. }
  42. impl fmt::Display for SyncError {
  43. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  44. write!(f, "{:?}: {}", &self.code, &self.msg)
  45. }
  46. }
  47. #[derive(Debug, Clone, Display, PartialEq, Eq)]
  48. pub enum ErrorCode {
  49. DocumentIdInvalid = 0,
  50. DocumentNotfound = 1,
  51. UndoFail = 200,
  52. RedoFail = 201,
  53. OutOfBound = 202,
  54. RevisionConflict = 203,
  55. RecordNotFound = 300,
  56. CannotDeleteThePrimaryField = 301,
  57. UnexpectedEmptyRevision = 302,
  58. SerdeError = 999,
  59. InternalError = 1000,
  60. }
  61. impl std::convert::From<lib_ot::errors::OTError> for SyncError {
  62. fn from(error: lib_ot::errors::OTError) -> Self {
  63. SyncError::new(ErrorCode::InternalError, "").context(error)
  64. }
  65. }
  66. // impl std::convert::From<protobuf::ProtobufError> for SyncError {
  67. // fn from(e: protobuf::ProtobufError) -> Self {
  68. // SyncError::internal().context(e)
  69. // }
  70. // }
  71. pub fn internal_sync_error<T>(e: T) -> SyncError
  72. where
  73. T: std::fmt::Debug,
  74. {
  75. SyncError::internal().context(e)
  76. }