errors.rs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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: &str) -> OTError {
  25. Self {
  26. code,
  27. msg: msg.to_owned(),
  28. }
  29. }
  30. pub fn context<T: Debug>(mut self, error: T) -> Self {
  31. self.msg = format!("{:?}", error);
  32. self
  33. }
  34. static_ot_error!(duplicate_revision, OTErrorCode::DuplicatedRevision);
  35. static_ot_error!(revision_id_conflict, OTErrorCode::RevisionIDConflict);
  36. static_ot_error!(internal, OTErrorCode::Internal);
  37. }
  38. impl fmt::Display for OTError {
  39. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  40. write!(f, "incompatible lengths")
  41. }
  42. }
  43. impl std::convert::From<serde_json::Error> for OTError {
  44. fn from(error: serde_json::Error) -> Self {
  45. ErrorBuilder::new(OTErrorCode::SerdeError).error(error).build()
  46. }
  47. }
  48. impl std::convert::From<Utf8Error> for OTError {
  49. fn from(error: Utf8Error) -> Self {
  50. ErrorBuilder::new(OTErrorCode::SerdeError).error(error).build()
  51. }
  52. }
  53. #[derive(Debug, Clone)]
  54. pub enum OTErrorCode {
  55. IncompatibleLength,
  56. ApplyInsertFail,
  57. ApplyDeleteFail,
  58. ApplyFormatFail,
  59. ComposeOperationFail,
  60. IntervalOutOfBound,
  61. UndoFail,
  62. RedoFail,
  63. SerdeError,
  64. DuplicatedRevision,
  65. RevisionIDConflict,
  66. Internal,
  67. }
  68. pub struct ErrorBuilder {
  69. pub code: OTErrorCode,
  70. pub msg: Option<String>,
  71. }
  72. impl ErrorBuilder {
  73. pub fn new(code: OTErrorCode) -> Self {
  74. ErrorBuilder { code, msg: None }
  75. }
  76. pub fn msg<T>(mut self, msg: T) -> Self
  77. where
  78. T: Into<String>,
  79. {
  80. self.msg = Some(msg.into());
  81. self
  82. }
  83. pub fn error<T>(mut self, msg: T) -> Self
  84. where
  85. T: std::fmt::Debug,
  86. {
  87. self.msg = Some(format!("{:?}", msg));
  88. self
  89. }
  90. pub fn build(mut self) -> OTError {
  91. OTError::new(self.code, &self.msg.take().unwrap_or_else(|| "".to_owned()))
  92. }
  93. }