errors.rs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. UndoFail,
  27. RedoFail,
  28. }
  29. pub struct ErrorBuilder {
  30. pub code: OTErrorCode,
  31. pub msg: Option<String>,
  32. }
  33. impl ErrorBuilder {
  34. pub fn new(code: OTErrorCode) -> Self { ErrorBuilder { code, msg: None } }
  35. pub fn msg<T>(mut self, msg: T) -> Self
  36. where
  37. T: Into<String>,
  38. {
  39. self.msg = Some(msg.into());
  40. self
  41. }
  42. pub fn error<T>(mut self, msg: T) -> Self
  43. where
  44. T: std::fmt::Debug,
  45. {
  46. self.msg = Some(format!("{:?}", msg));
  47. self
  48. }
  49. pub fn build(mut self) -> OTError {
  50. OTError::new(self.code, &self.msg.take().unwrap_or("".to_owned()))
  51. }
  52. }