errors.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. use std::{error::Error, fmt};
  2. #[derive(Clone, Debug)]
  3. pub struct OTError {
  4. pub code: OTErrorCode,
  5. pub msg: String,
  6. }
  7. impl OTError {
  8. pub fn new(code: OTErrorCode, msg: &str) -> OTError {
  9. Self {
  10. code,
  11. msg: msg.to_owned(),
  12. }
  13. }
  14. }
  15. impl fmt::Display for OTError {
  16. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "incompatible lengths") }
  17. }
  18. impl Error for OTError {
  19. fn source(&self) -> Option<&(dyn Error + 'static)> { None }
  20. }
  21. #[derive(Debug, Clone)]
  22. pub enum OTErrorCode {
  23. IncompatibleLength,
  24. ApplyInsertFail,
  25. ApplyFormatFail,
  26. ComposeOperationFail,
  27. UndoFail,
  28. RedoFail,
  29. }
  30. pub struct ErrorBuilder {
  31. pub code: OTErrorCode,
  32. pub msg: Option<String>,
  33. }
  34. impl ErrorBuilder {
  35. pub fn new(code: OTErrorCode) -> Self { ErrorBuilder { code, msg: None } }
  36. pub fn msg<T>(mut self, msg: T) -> Self
  37. where
  38. T: Into<String>,
  39. {
  40. self.msg = Some(msg.into());
  41. self
  42. }
  43. pub fn error<T>(mut self, msg: T) -> Self
  44. where
  45. T: std::fmt::Debug,
  46. {
  47. self.msg = Some(format!("{:?}", msg));
  48. self
  49. }
  50. pub fn build(mut self) -> OTError {
  51. OTError::new(self.code, &self.msg.take().unwrap_or("".to_owned()))
  52. }
  53. }