Skip to main content

xmachines_runtime/
error.rs

1use std::fmt;
2
3/// What went wrong while loading a machine definition.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum LoadErrorKind {
6    /// The definition is not valid JSON, or a value has the wrong shape.
7    Invalid,
8    /// A `{"@code": ...}` or `{"@expr": ...}` node that is malformed, or in a language with no evaluator.
9    Code,
10    /// A key that `machineFromJSON` does not accept.
11    UnknownKey,
12    /// A v6 feature this runtime does not support (yet).
13    Unsupported,
14    /// A transition target, `initial`, history target or `stateIn` id that does not resolve.
15    InvalidTarget,
16    /// A guard, action or delay referenced by name with no implementation.
17    MissingImplementation,
18    /// An implementation rejected the `params` it was given.
19    InvalidParams,
20    /// Two states share an id.
21    DuplicateId,
22}
23
24/// An error raised while parsing, validating or compiling a machine definition.
25///
26/// `path` is a JSON path in the style XState uses, for example
27/// `$.states.idle.on.go[0].guard`.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct LoadError {
30    pub kind: LoadErrorKind,
31    pub path: String,
32    pub message: String,
33}
34
35impl LoadError {
36    pub(crate) fn new(kind: LoadErrorKind, path: impl Into<String>, message: impl Into<String>) -> Self {
37        Self { kind, path: path.into(), message: message.into() }
38    }
39}
40
41impl fmt::Display for LoadError {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        write!(f, "{} at {}", self.message, self.path)
44    }
45}
46
47impl std::error::Error for LoadError {}
48
49/// One value of an XState error code's message: a string, quoted as
50/// `JSON.stringify` quotes it, or any other value as `String(value)` writes it.
51pub(crate) enum CodeValue<'a> {
52    Str(&'a str),
53    Raw(&'a str),
54}
55
56/// The message of an error XState reports as a code (its production
57/// message, `xstateError`): the code, the values that identify what failed,
58/// and a link to the code's entry in XState's error reference.
59pub(crate) fn xstate_error(code: u32, values: &[CodeValue<'_>]) -> String {
60    let mut message = format!("XState error E{code}");
61    if !values.is_empty() {
62        let values: Vec<String> = values
63            .iter()
64            .map(|v| match v {
65                CodeValue::Str(s) => serde_json::Value::String((*s).to_owned()).to_string(),
66                CodeValue::Raw(s) => (*s).to_owned(),
67            })
68            .collect();
69        message.push_str(&format!(" ({})", values.join(", ")));
70    }
71    message.push_str(&format!(". See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e{code}"));
72    message
73}