Skip to main content

kira_scio/
error.rs

1use std::path::PathBuf;
2
3use thiserror::Error;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum ErrorCode {
7    InvalidInputPath,
8    MissingFile,
9    UnsupportedFormat,
10    ParseError,
11    DimensionMismatch,
12    ValidationError,
13    FeatureDisabled,
14    Io,
15}
16
17#[derive(Debug, Error)]
18pub struct ScioError {
19    pub code: ErrorCode,
20    pub message: String,
21    pub path: Option<PathBuf>,
22    #[source]
23    pub source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
24}
25
26impl ScioError {
27    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
28        Self {
29            code,
30            message: message.into(),
31            path: None,
32            source: None,
33        }
34    }
35
36    pub fn with_path(mut self, path: impl Into<PathBuf>) -> Self {
37        self.path = Some(path.into());
38        self
39    }
40
41    pub fn with_source<E>(mut self, source: E) -> Self
42    where
43        E: std::error::Error + Send + Sync + 'static,
44    {
45        self.source = Some(Box::new(source));
46        self
47    }
48}
49
50impl Clone for ScioError {
51    fn clone(&self) -> Self {
52        Self {
53            code: self.code,
54            message: self.message.clone(),
55            path: self.path.clone(),
56            source: None,
57        }
58    }
59}
60
61impl std::fmt::Display for ScioError {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        match self.path.as_ref() {
64            Some(p) => write!(f, "{:?} [{}]: {}", self.code, p.display(), self.message),
65            None => write!(f, "{:?}: {}", self.code, self.message),
66        }
67    }
68}
69
70impl From<std::io::Error> for ScioError {
71    fn from(value: std::io::Error) -> Self {
72        let msg = value.to_string();
73        ScioError::new(ErrorCode::Io, msg).with_source(value)
74    }
75}
76
77pub type ScioResult<T> = Result<T, ScioError>;