Skip to main content

ocpp_kit/rpc/
error.rs

1//! OCPP-J error codes and `CALLERROR` payloads.
2
3use alloc::borrow::{Cow, ToOwned};
4use alloc::format;
5use alloc::string::{String, ToString};
6use core::fmt;
7
8use crate::decode::{DecodeError, DecodeErrorKind};
9use crate::version::Version;
10
11/// An OCPP-J RPC framework error code (2.1 Part 4 Table 9; 1.6J Table 7).
12///
13/// The wire spelling is version-dependent and the differences are not cosmetic:
14///
15/// | Variant | 1.6J | 2.0.1 / 2.1 |
16/// |---|---|---|
17/// | [`FormatViolation`](Self::FormatViolation) | `FormationViolation` | `FormatViolation` |
18/// | [`OccurrenceConstraintViolation`](Self::OccurrenceConstraintViolation) | `OccurenceConstraintViolation` (one `r`, as printed in the specification) | `OccurrenceConstraintViolation` |
19/// | [`RpcFrameworkError`](Self::RpcFrameworkError) | not defined — sent as `GenericError` | `RpcFrameworkError` |
20/// | [`MessageTypeNotSupported`](Self::MessageTypeNotSupported) | not defined — sent as `GenericError` | `MessageTypeNotSupported` (deprecated; never sent) |
21///
22/// Parsing accepts every spelling on every version, because peers mix them up constantly.
23#[derive(Clone, Debug, PartialEq, Eq, Hash)]
24#[non_exhaustive]
25pub enum ErrorCode {
26    /// The payload is syntactically incorrect.
27    FormatViolation,
28    /// Any error not covered by a more specific code.
29    GenericError,
30    /// The receiver failed internally while processing the action.
31    InternalError,
32    /// A message type number the receiver does not support (2.x only).
33    ///
34    /// Deprecated by the 2.0.1 edition 4 errata (2026-02): an unknown message type is
35    /// ignored on every version, so this engine never sends it. Still parsed, because older
36    /// 2.0.1 peers do.
37    MessageTypeNotSupported,
38    /// The requested action is not known to the receiver.
39    NotImplemented,
40    /// The action is known but not supported by the receiver.
41    NotSupported,
42    /// A field violates an occurrence constraint.
43    OccurrenceConstraintViolation,
44    /// A field contains an invalid value.
45    PropertyConstraintViolation,
46    /// The payload does not conform to the action's PDU structure.
47    ProtocolError,
48    /// The message is not a valid RPC request — for example the `MessageId` could not be
49    /// read (2.x only).
50    RpcFrameworkError,
51    /// A security issue prevented the receiver from completing the action.
52    SecurityError,
53    /// A field violates a data-type constraint.
54    TypeConstraintViolation,
55    /// A code this crate does not define, kept verbatim.
56    Other(String),
57}
58
59impl ErrorCode {
60    /// The spelling this code uses on the wire for `version`.
61    ///
62    /// Codes that a version does not define are downgraded to `GenericError`, which is the
63    /// only code 1.6J offers for "something else went wrong".
64    #[must_use]
65    pub fn as_wire(&self, version: Version) -> &str {
66        let legacy = version == Version::V1_6;
67        match self {
68            ErrorCode::FormatViolation => {
69                if legacy {
70                    "FormationViolation"
71                } else {
72                    "FormatViolation"
73                }
74            }
75            ErrorCode::GenericError => "GenericError",
76            ErrorCode::InternalError => "InternalError",
77            ErrorCode::MessageTypeNotSupported => {
78                if legacy {
79                    "GenericError"
80                } else {
81                    "MessageTypeNotSupported"
82                }
83            }
84            ErrorCode::NotImplemented => "NotImplemented",
85            ErrorCode::NotSupported => "NotSupported",
86            ErrorCode::OccurrenceConstraintViolation => {
87                if legacy {
88                    // The 1.6J specification prints it with a single `r`.
89                    "OccurenceConstraintViolation"
90                } else {
91                    "OccurrenceConstraintViolation"
92                }
93            }
94            ErrorCode::PropertyConstraintViolation => "PropertyConstraintViolation",
95            ErrorCode::ProtocolError => "ProtocolError",
96            ErrorCode::RpcFrameworkError => {
97                if legacy {
98                    "GenericError"
99                } else {
100                    "RpcFrameworkError"
101                }
102            }
103            ErrorCode::SecurityError => "SecurityError",
104            ErrorCode::TypeConstraintViolation => "TypeConstraintViolation",
105            ErrorCode::Other(code) => code.as_str(),
106        }
107    }
108
109    /// Parses a wire code, accepting every version's spelling.
110    #[must_use]
111    pub fn parse(code: &str) -> Self {
112        match code {
113            "FormatViolation" | "FormationViolation" => ErrorCode::FormatViolation,
114            "GenericError" => ErrorCode::GenericError,
115            "InternalError" => ErrorCode::InternalError,
116            "MessageTypeNotSupported" => ErrorCode::MessageTypeNotSupported,
117            "NotImplemented" => ErrorCode::NotImplemented,
118            "NotSupported" => ErrorCode::NotSupported,
119            "OccurrenceConstraintViolation" | "OccurenceConstraintViolation" => {
120                ErrorCode::OccurrenceConstraintViolation
121            }
122            "PropertyConstraintViolation" => ErrorCode::PropertyConstraintViolation,
123            "ProtocolError" => ErrorCode::ProtocolError,
124            "RpcFrameworkError" => ErrorCode::RpcFrameworkError,
125            "SecurityError" => ErrorCode::SecurityError,
126            "TypeConstraintViolation" => ErrorCode::TypeConstraintViolation,
127            other => ErrorCode::Other(other.to_owned()),
128        }
129    }
130
131    /// Whether `version` defines this code at all.
132    #[must_use]
133    pub fn is_defined_in(&self, version: Version) -> bool {
134        match self {
135            ErrorCode::RpcFrameworkError | ErrorCode::MessageTypeNotSupported => {
136                version != Version::V1_6
137            }
138            ErrorCode::Other(_) => false,
139            _ => true,
140        }
141    }
142}
143
144impl fmt::Display for ErrorCode {
145    /// Uses the 2.x spelling; call [`as_wire`](Self::as_wire) when the version matters.
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        f.write_str(self.as_wire(Version::V2_1))
148    }
149}
150
151/// The longest `errorDescription` the specification allows (Part 4, Table 7).
152pub const ERROR_DESCRIPTION_MAX_LEN: usize = 255;
153
154/// Truncates a description to the length the wire format allows.
155///
156/// Descriptions are built from decoding failures, which quote paths and values and can run
157/// long. Emitting an over-long one would be a violation in the very message that reports a
158/// violation.
159fn cap_description(text: &str) -> String {
160    match text.char_indices().nth(ERROR_DESCRIPTION_MAX_LEN) {
161        Some((cut, _)) => text[..cut].to_owned(),
162        None => text.to_owned(),
163    }
164}
165
166/// The body of a `CALLERROR` (or, in 2.1, a `CALLRESULTERROR`).
167#[derive(Clone, Debug, PartialEq)]
168pub struct CallError {
169    /// The RPC framework error code.
170    pub code: ErrorCode,
171    /// Short human-readable description. Empty is allowed; the spec suggests `""`.
172    pub description: String,
173    /// Free-form details object. Never `null` on the wire — an empty object is used.
174    pub details: serde_json::Value,
175}
176
177impl CallError {
178    /// Builds a `CALLERROR` body with an empty details object.
179    #[must_use]
180    pub fn new(code: ErrorCode, description: impl Into<String>) -> Self {
181        Self {
182            code,
183            description: cap_description(&description.into()),
184            details: serde_json::Value::Object(serde_json::Map::new()),
185        }
186    }
187
188    /// Attaches a details object.
189    #[must_use]
190    pub fn with_details(mut self, details: serde_json::Value) -> Self {
191        self.details = details;
192        self
193    }
194
195    /// The action is not known to this implementation.
196    #[must_use]
197    pub fn not_implemented(action: &str) -> Self {
198        Self::new(
199            ErrorCode::NotImplemented,
200            format!("unknown action {action:?}"),
201        )
202    }
203
204    /// The action is known but this peer does not handle it.
205    #[must_use]
206    pub fn not_supported(action: &str) -> Self {
207        Self::new(
208            ErrorCode::NotSupported,
209            format!("action {action:?} is not supported"),
210        )
211    }
212
213    /// The handler failed.
214    #[must_use]
215    pub fn internal(description: impl Into<String>) -> Self {
216        Self::new(ErrorCode::InternalError, description)
217    }
218
219    /// A security check failed while processing the action.
220    #[must_use]
221    pub fn security(description: impl Into<String>) -> Self {
222        Self::new(ErrorCode::SecurityError, description)
223    }
224}
225
226impl From<DecodeError> for CallError {
227    /// Maps a decoding failure onto the error code the specification prescribes, and puts
228    /// the offending JSON pointer into `errorDetails` so the peer can find it.
229    fn from(error: DecodeError) -> Self {
230        let code = match error.kind {
231            DecodeErrorKind::Format => ErrorCode::FormatViolation,
232            DecodeErrorKind::Occurrence => ErrorCode::OccurrenceConstraintViolation,
233            DecodeErrorKind::Type => ErrorCode::TypeConstraintViolation,
234            DecodeErrorKind::Property => ErrorCode::PropertyConstraintViolation,
235            // "Payload for Action is not conform the PDU structure" — an undefined member is
236            // exactly that, since the 2.x schemas set `additionalProperties: false`.
237            DecodeErrorKind::UnknownField | DecodeErrorKind::Protocol => ErrorCode::ProtocolError,
238            DecodeErrorKind::UnsupportedAction => ErrorCode::NotSupported,
239        };
240        let mut details = serde_json::Map::new();
241        if !error.path.is_empty() {
242            details.insert(
243                "path".to_string(),
244                serde_json::Value::String(error.path.clone()),
245            );
246        }
247        details.insert(
248            "reason".to_string(),
249            serde_json::Value::String(error.reason.clone()),
250        );
251        Self {
252            code,
253            description: cap_description(&error.to_string()),
254            details: serde_json::Value::Object(details),
255        }
256    }
257}
258
259impl fmt::Display for CallError {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        if self.description.is_empty() {
262            write!(f, "{}", self.code)
263        } else {
264            write!(f, "{}: {}", self.code, self.description)
265        }
266    }
267}
268
269#[cfg(feature = "std")]
270impl std::error::Error for CallError {}
271
272/// Borrowed form of [`CallError`], as produced by frame parsing.
273///
274/// The details object stays unparsed so a Local Controller can relay it untouched.
275#[derive(Clone, Debug)]
276pub struct CallErrorRef<'a> {
277    /// The RPC framework error code.
278    pub code: ErrorCode,
279    /// Short human-readable description.
280    pub description: Cow<'a, str>,
281    /// Free-form details object, still unparsed.
282    pub details: Cow<'a, serde_json::value::RawValue>,
283}
284
285impl CallErrorRef<'_> {
286    /// Copies the borrowed error into an owned [`CallError`].
287    #[must_use]
288    pub fn to_call_error(&self) -> CallError {
289        CallError {
290            code: self.code.clone(),
291            description: self.description.clone().into_owned(),
292            details: serde_json::from_str(self.details.get())
293                .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new())),
294        }
295    }
296
297    /// Detaches the error from the buffer it was parsed from.
298    #[must_use]
299    pub fn into_owned(self) -> CallErrorRef<'static> {
300        CallErrorRef {
301            code: self.code,
302            description: Cow::Owned(self.description.into_owned()),
303            details: Cow::Owned(self.details.into_owned()),
304        }
305    }
306}
307
308impl PartialEq for CallErrorRef<'_> {
309    /// Compares the details object by its raw JSON text.
310    fn eq(&self, other: &Self) -> bool {
311        self.code == other.code
312            && self.description == other.description
313            && self.details.get() == other.details.get()
314    }
315}
316
317impl From<CallError> for CallErrorRef<'static> {
318    fn from(error: CallError) -> Self {
319        CallErrorRef {
320            code: error.code,
321            description: Cow::Owned(cap_description(&error.description)),
322            details: Cow::Owned(
323                serde_json::value::to_raw_value(&error.details).unwrap_or_else(|_| {
324                    serde_json::value::RawValue::from_string("{}".to_string()).expect("valid")
325                }),
326            ),
327        }
328    }
329}
330
331impl From<&CallError> for CallErrorRef<'static> {
332    fn from(error: &CallError) -> Self {
333        CallErrorRef {
334            code: error.code.clone(),
335            description: Cow::Owned(cap_description(&error.description)),
336            details: Cow::Owned(
337                serde_json::value::to_raw_value(&error.details).unwrap_or_else(|_| {
338                    serde_json::value::RawValue::from_string("{}".to_string()).expect("valid")
339                }),
340            ),
341        }
342    }
343}