errors.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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() -> DocumentError {
  7. DocumentError {
  8. code: $status,
  9. msg: format!("{}", $status),
  10. }
  11. }
  12. };
  13. }
  14. pub type DocumentResult<T> = std::result::Result<T, DocumentError>;
  15. #[derive(Debug, Clone)]
  16. pub struct DocumentError {
  17. pub code: ErrorCode,
  18. pub msg: String,
  19. }
  20. impl DocumentError {
  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. }
  36. impl fmt::Display for DocumentError {
  37. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}: {}", &self.code, &self.msg) }
  38. }
  39. #[derive(Debug, Clone, Display, PartialEq, Eq)]
  40. pub enum ErrorCode {
  41. DocIdInvalid = 0,
  42. DocNotfound = 1,
  43. UndoFail = 200,
  44. RedoFail = 201,
  45. OutOfBound = 202,
  46. InternalError = 1000,
  47. }
  48. impl std::convert::From<lib_ot::errors::OTError> for DocumentError {
  49. fn from(error: lib_ot::errors::OTError) -> Self { DocumentError::new(ErrorCode::InternalError, "").context(error) }
  50. }
  51. impl std::convert::From<protobuf::ProtobufError> for DocumentError {
  52. fn from(e: protobuf::ProtobufError) -> Self { DocumentError::internal().context(e) }
  53. }