errors.rs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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!(internal, ErrorCode::InternalError);
  32. static_error!(undo, ErrorCode::UndoFail);
  33. static_error!(redo, ErrorCode::RedoFail);
  34. static_error!(out_of_bound, ErrorCode::OutOfBound);
  35. static_error!(record_not_found, ErrorCode::RecordNotFound);
  36. static_error!(revision_conflict, ErrorCode::RevisionConflict);
  37. static_error!(can_not_delete_primary_field, ErrorCode::CannotDeleteThePrimaryField);
  38. }
  39. impl fmt::Display for CollaborateError {
  40. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  41. write!(f, "{:?}: {}", &self.code, &self.msg)
  42. }
  43. }
  44. #[derive(Debug, Clone, Display, PartialEq, Eq)]
  45. pub enum ErrorCode {
  46. DocIdInvalid = 0,
  47. DocNotfound = 1,
  48. UndoFail = 200,
  49. RedoFail = 201,
  50. OutOfBound = 202,
  51. RevisionConflict = 203,
  52. RecordNotFound = 300,
  53. CannotDeleteThePrimaryField = 301,
  54. InternalError = 1000,
  55. }
  56. impl std::convert::From<lib_ot::errors::OTError> for CollaborateError {
  57. fn from(error: lib_ot::errors::OTError) -> Self {
  58. CollaborateError::new(ErrorCode::InternalError, "").context(error)
  59. }
  60. }
  61. impl std::convert::From<protobuf::ProtobufError> for CollaborateError {
  62. fn from(e: protobuf::ProtobufError) -> Self {
  63. CollaborateError::internal().context(e)
  64. }
  65. }
  66. pub(crate) fn internal_error<T>(e: T) -> CollaborateError
  67. where
  68. T: std::fmt::Debug,
  69. {
  70. CollaborateError::internal().context(e)
  71. }