Skip to main content

fidius_core/
error.rs

1// Copyright 2026 Colliery, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Error types for the Fidius plugin framework.
16
17use serde::{Deserialize, Serialize};
18use std::fmt;
19
20/// Error returned by plugin method implementations to signal business logic failures.
21///
22/// Serialized across the FFI boundary via the wire format. The host deserializes
23/// this from the output buffer when the FFI shim returns `STATUS_PLUGIN_ERROR`.
24///
25/// The `details` field is stored as a JSON string (not `serde_json::Value`)
26/// so that it serializes correctly under both JSON and bincode wire formats.
27#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
28pub struct PluginError {
29    /// Machine-readable error code (e.g., `"INVALID_INPUT"`, `"NOT_FOUND"`).
30    pub code: String,
31    /// Human-readable error message.
32    pub message: String,
33    /// Optional structured details as a JSON string.
34    pub details: Option<String>,
35}
36
37impl PluginError {
38    /// Create a new `PluginError` without details.
39    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
40        Self {
41            code: code.into(),
42            message: message.into(),
43            details: None,
44        }
45    }
46
47    /// Create a new `PluginError` with structured details.
48    ///
49    /// The `serde_json::Value` is serialized to a JSON string for storage.
50    pub fn with_details(
51        code: impl Into<String>,
52        message: impl Into<String>,
53        details: serde_json::Value,
54    ) -> Self {
55        Self {
56            code: code.into(),
57            message: message.into(),
58            details: Some(details.to_string()),
59        }
60    }
61
62    /// Parse the `details` field back into a `serde_json::Value`.
63    ///
64    /// Returns `None` if details is absent or fails to parse.
65    pub fn details_value(&self) -> Option<serde_json::Value> {
66        self.details
67            .as_deref()
68            .and_then(|s| serde_json::from_str(s).ok())
69    }
70}
71
72impl fmt::Display for PluginError {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        write!(f, "[{}] {}", self.code, self.message)
75    }
76}
77
78impl std::error::Error for PluginError {}