errors.rs 2.1 KB

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