errors.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. use std::{fmt, fmt::Debug, str::Utf8Error};
  2. #[derive(thiserror::Error, Clone, Debug)]
  3. pub struct OTError {
  4. pub code: OTErrorCode,
  5. pub msg: String,
  6. }
  7. macro_rules! static_ot_error {
  8. ($name:ident, $code:expr) => {
  9. #[allow(non_snake_case, missing_docs)]
  10. pub fn $name() -> OTError {
  11. $code.into()
  12. }
  13. };
  14. }
  15. impl std::convert::From<OTErrorCode> for OTError {
  16. fn from(code: OTErrorCode) -> Self {
  17. OTError {
  18. code: code.clone(),
  19. msg: format!("{:?}", code),
  20. }
  21. }
  22. }
  23. impl OTError {
  24. pub fn new(code: OTErrorCode, msg: String) -> OTError {
  25. Self { code, msg }
  26. }
  27. pub fn context<T: Debug>(mut self, error: T) -> Self {
  28. self.msg = format!("{:?}", error);
  29. self
  30. }
  31. static_ot_error!(duplicate_revision, OTErrorCode::DuplicatedRevision);
  32. static_ot_error!(revision_id_conflict, OTErrorCode::RevisionIDConflict);
  33. static_ot_error!(internal, OTErrorCode::Internal);
  34. static_ot_error!(serde, OTErrorCode::SerdeError);
  35. }
  36. impl fmt::Display for OTError {
  37. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  38. write!(f, "incompatible lengths")
  39. }
  40. }
  41. impl std::convert::From<serde_json::Error> for OTError {
  42. fn from(error: serde_json::Error) -> Self {
  43. ErrorBuilder::new(OTErrorCode::SerdeError).error(error).build()
  44. }
  45. }
  46. impl std::convert::From<Utf8Error> for OTError {
  47. fn from(error: Utf8Error) -> Self {
  48. ErrorBuilder::new(OTErrorCode::SerdeError).error(error).build()
  49. }
  50. }
  51. #[derive(Debug, Clone, Eq, PartialEq)]
  52. pub enum OTErrorCode {
  53. IncompatibleLength,
  54. ApplyInsertFail,
  55. ApplyDeleteFail,
  56. ApplyFormatFail,
  57. ComposeOperationFail,
  58. IntervalOutOfBound,
  59. UndoFail,
  60. RedoFail,
  61. SerdeError,
  62. DuplicatedRevision,
  63. RevisionIDConflict,
  64. Internal,
  65. PathNotFound,
  66. PathIsEmpty,
  67. UnexpectedEmpty,
  68. }
  69. pub struct ErrorBuilder {
  70. pub code: OTErrorCode,
  71. pub msg: Option<String>,
  72. }
  73. impl ErrorBuilder {
  74. pub fn new(code: OTErrorCode) -> Self {
  75. ErrorBuilder { code, msg: None }
  76. }
  77. pub fn msg<T>(mut self, msg: T) -> Self
  78. where
  79. T: Into<String>,
  80. {
  81. self.msg = Some(msg.into());
  82. self
  83. }
  84. pub fn error<T>(mut self, msg: T) -> Self
  85. where
  86. T: std::fmt::Debug,
  87. {
  88. self.msg = Some(format!("{:?}", msg));
  89. self
  90. }
  91. pub fn build(mut self) -> OTError {
  92. OTError::new(self.code, self.msg.take().unwrap_or_else(|| "".to_owned()))
  93. }
  94. }