Skip to main content

cymule_core/
error.rs

1use std::fmt::{Display, Formatter};
2
3/// Result type used by the semantic kernel.
4pub type Result<T> = std::result::Result<T, CoreError>;
5
6/// Stable semantic error categories.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum CoreError {
9    /// An object failed semantic validation.
10    Validation(String),
11    /// A referenced object does not exist.
12    NotFound(String),
13    /// An immutable identity did not match its content.
14    IdentityMismatch(String),
15    /// A state-machine transition is not legal.
16    IllegalTransition(String),
17    /// A command ID was reused with different semantics.
18    CommandReuse(String),
19    /// A causal parent is missing or the event graph is cyclic.
20    Causal(String),
21    /// Canonical encoding failed.
22    Encoding(String),
23}
24
25impl CoreError {
26    /// Stable machine-readable error code.
27    pub const fn code(&self) -> &'static str {
28        match self {
29            Self::Validation(_) => "validation_failed",
30            Self::NotFound(_) => "not_found",
31            Self::IdentityMismatch(_) => "identity_mismatch",
32            Self::IllegalTransition(_) => "illegal_transition",
33            Self::CommandReuse(_) => "command_id_reused",
34            Self::Causal(_) => "causal_error",
35            Self::Encoding(_) => "encoding_failed",
36        }
37    }
38}
39
40impl Display for CoreError {
41    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
42        let message = match self {
43            Self::Validation(message)
44            | Self::NotFound(message)
45            | Self::IdentityMismatch(message)
46            | Self::IllegalTransition(message)
47            | Self::CommandReuse(message)
48            | Self::Causal(message)
49            | Self::Encoding(message) => message,
50        };
51        write!(formatter, "{}: {message}", self.code())
52    }
53}
54
55impl std::error::Error for CoreError {}
56
57impl From<serde_json::Error> for CoreError {
58    fn from(error: serde_json::Error) -> Self {
59        Self::Encoding(error.to_string())
60    }
61}