AppFlowy/shared-lib/flowy-sync/src/errors.rs

81 lines
2.1 KiB
Rust
Raw Normal View History

2021-11-19 04:18:46 +00:00
use std::{fmt, fmt::Debug};
use strum_macros::Display;
macro_rules! static_doc_error {
($name:ident, $status:expr) => {
#[allow(non_snake_case, missing_docs)]
pub fn $name() -> CollaborateError {
CollaborateError {
2021-11-19 04:18:46 +00:00
code: $status,
msg: format!("{}", $status),
}
}
};
}
pub type CollaborateResult<T> = std::result::Result<T, CollaborateError>;
2021-11-19 04:18:46 +00:00
#[derive(Debug, Clone)]
pub struct CollaborateError {
2021-11-19 04:18:46 +00:00
pub code: ErrorCode,
pub msg: String,
}
impl CollaborateError {
2021-11-19 04:18:46 +00:00
fn new(code: ErrorCode, msg: &str) -> Self {
Self {
code,
msg: msg.to_owned(),
}
}
pub fn context<T: Debug>(mut self, error: T) -> Self {
self.msg = format!("{:?}", error);
self
}
static_doc_error!(internal, ErrorCode::InternalError);
static_doc_error!(undo, ErrorCode::UndoFail);
static_doc_error!(redo, ErrorCode::RedoFail);
static_doc_error!(out_of_bound, ErrorCode::OutOfBound);
2021-12-13 14:46:35 +00:00
static_doc_error!(record_not_found, ErrorCode::RecordNotFound);
static_doc_error!(revision_conflict, ErrorCode::RevisionConflict);
2021-11-19 04:18:46 +00:00
}
impl fmt::Display for CollaborateError {
2022-01-23 04:14:00 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}: {}", &self.code, &self.msg)
}
2021-11-19 04:18:46 +00:00
}
#[derive(Debug, Clone, Display, PartialEq, Eq)]
pub enum ErrorCode {
2022-01-23 04:14:00 +00:00
DocIdInvalid = 0,
DocNotfound = 1,
UndoFail = 200,
RedoFail = 201,
OutOfBound = 202,
2021-12-13 14:46:35 +00:00
RevisionConflict = 203,
2022-01-23 04:14:00 +00:00
RecordNotFound = 300,
InternalError = 1000,
2021-11-19 04:18:46 +00:00
}
impl std::convert::From<lib_ot::errors::OTError> for CollaborateError {
fn from(error: lib_ot::errors::OTError) -> Self {
CollaborateError::new(ErrorCode::InternalError, "").context(error)
}
}
impl std::convert::From<protobuf::ProtobufError> for CollaborateError {
2022-01-23 04:14:00 +00:00
fn from(e: protobuf::ProtobufError) -> Self {
CollaborateError::internal().context(e)
}
2021-11-19 04:18:46 +00:00
}
pub(crate) fn internal_error<T>(e: T) -> CollaborateError
where
T: std::fmt::Debug,
{
CollaborateError::internal().context(e)
2021-11-19 04:18:46 +00:00
}