AppFlowy/rust-lib/flowy-ot/src/errors.rs

75 lines
1.5 KiB
Rust
Raw Normal View History

2021-07-31 12:53:45 +00:00
use std::{error::Error, fmt};
#[derive(Clone, Debug)]
2021-08-05 14:52:19 +00:00
pub struct OTError {
pub code: OTErrorCode,
pub msg: String,
}
impl OTError {
pub fn new(code: OTErrorCode, msg: &str) -> OTError {
Self {
code,
msg: msg.to_owned(),
}
}
}
2021-07-31 12:53:45 +00:00
impl fmt::Display for OTError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "incompatible lengths") }
}
impl Error for OTError {
fn source(&self) -> Option<&(dyn Error + 'static)> { None }
}
2021-08-05 14:52:19 +00:00
2021-08-18 08:04:22 +00:00
impl std::convert::From<serde_json::Error> for OTError {
fn from(error: serde_json::Error) -> Self {
ErrorBuilder::new(OTErrorCode::SerdeError)
.error(error)
.build()
}
}
2021-08-05 14:52:19 +00:00
#[derive(Debug, Clone)]
pub enum OTErrorCode {
IncompatibleLength,
2021-08-11 15:34:35 +00:00
ApplyInsertFail,
2021-08-14 16:05:18 +00:00
ApplyDeleteFail,
2021-08-11 15:34:35 +00:00
ApplyFormatFail,
2021-08-14 08:44:39 +00:00
ComposeOperationFail,
2021-08-14 16:05:18 +00:00
IntervalOutOfBound,
2021-08-05 14:52:19 +00:00
UndoFail,
RedoFail,
2021-08-18 08:04:22 +00:00
SerdeError,
2021-08-05 14:52:19 +00:00
}
pub struct ErrorBuilder {
pub code: OTErrorCode,
pub msg: Option<String>,
}
impl ErrorBuilder {
pub fn new(code: OTErrorCode) -> Self { ErrorBuilder { code, msg: None } }
pub fn msg<T>(mut self, msg: T) -> Self
where
T: Into<String>,
{
self.msg = Some(msg.into());
self
}
pub fn error<T>(mut self, msg: T) -> Self
where
T: std::fmt::Debug,
{
self.msg = Some(format!("{:?}", msg));
self
}
pub fn build(mut self) -> OTError {
OTError::new(self.code, &self.msg.take().unwrap_or("".to_owned()))
}
}