errors.rs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. impl std::convert::From<serde_json::Error> for OTError {
  22. fn from(error: serde_json::Error) -> Self {
  23. ErrorBuilder::new(OTErrorCode::SerdeError)
  24. .error(error)
  25. .build()
  26. }
  27. }
  28. #[derive(Debug, Clone)]
  29. pub enum OTErrorCode {
  30. IncompatibleLength,
  31. ApplyInsertFail,
  32. ApplyDeleteFail,
  33. ApplyFormatFail,
  34. ComposeOperationFail,
  35. IntervalOutOfBound,
  36. UndoFail,
  37. RedoFail,
  38. SerdeError,
  39. }
  40. pub struct ErrorBuilder {
  41. pub code: OTErrorCode,
  42. pub msg: Option<String>,
  43. }
  44. impl ErrorBuilder {
  45. pub fn new(code: OTErrorCode) -> Self { ErrorBuilder { code, msg: None } }
  46. pub fn msg<T>(mut self, msg: T) -> Self
  47. where
  48. T: Into<String>,
  49. {
  50. self.msg = Some(msg.into());
  51. self
  52. }
  53. pub fn error<T>(mut self, msg: T) -> Self
  54. where
  55. T: std::fmt::Debug,
  56. {
  57. self.msg = Some(format!("{:?}", msg));
  58. self
  59. }
  60. pub fn build(mut self) -> OTError {
  61. OTError::new(self.code, &self.msg.take().unwrap_or("".to_owned()))
  62. }
  63. }