use std::{
convert::Infallible,
error::Error,
fmt::{Debug, Display, Formatter},
};
use crate::ObjectID;
use std::path::PathBuf;
pub type Result<T> = std::result::Result<T, YsError>;
pub struct YsError {
kind: Box<YsErrorKind>,
}
impl YsError {
pub fn path_error<P: Into<PathBuf>>(error: std::io::Error, path: P) -> Self {
Self { kind: Box::new(YsErrorKind::IO { error, path: Some(path.into()) }) }
}
}
impl Error for YsError {}
impl Debug for YsError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self.kind, f)
}
}
impl Display for YsError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.kind, f)
}
}
#[derive(Debug)]
pub enum YsErrorKind {
IO {
error: std::io::Error,
path: Option<PathBuf>,
},
Serde {
error: serde_json::Error,
},
MissingObject {
id: ObjectID,
},
}
impl Display for YsErrorKind {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::IO { .. } => {
todo!()
}
Self::Serde { .. } => {
todo!()
}
Self::MissingObject { id } => {
write!(f, "找不到对象: {}", id)
}
}
}
}
impl From<YsErrorKind> for YsError {
fn from(error: YsErrorKind) -> Self {
YsError { kind: Box::new(error) }
}
}
impl From<Infallible> for YsError {
fn from(_: Infallible) -> Self {
unreachable!()
}
}
impl From<std::io::Error> for YsError {
fn from(error: std::io::Error) -> Self {
YsErrorKind::IO { error, path: None }.into()
}
}
impl From<serde_json::Error> for YsError {
fn from(error: serde_json::Error) -> Self {
YsErrorKind::Serde { error }.into()
}
}