errors.rs 2.2 KB

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