errors.rs 1.6 KB

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