Skip to main content

trusty_code/jsonrpc/
error.rs

1//! Typed JSON-RPC error returned by [`super::router::MethodHandler`] impls.
2//!
3//! Why: handlers need a lightweight, typed way to signal a specific JSON-RPC
4//! error code (invalid params, internal error, …) without the router having
5//! to string-sniff an `anyhow::Error`. Centralising the constructors here
6//! means every handler produces spec-correct codes by construction.
7//! What: `RpcError { code, message, data }` plus constructors for the
8//! standard JSON-RPC 2.0 codes a handler is expected to return itself, and
9//! (#2054) the vision spec's domain error taxonomy (§13.2) — an
10//! *additive* layer of application-specific codes carried in the same
11//! envelope, each tagged with `data.error_type` so clients can match on a
12//! stable string rather than a numeric code alone. `-32601 Method not
13//! found` and `-32600 Invalid Request` are produced by
14//! [`super::router::Router`] before a handler is ever invoked, so they are
15//! intentionally not exposed as constructors here — a handler has no
16//! legitimate reason to fabricate either.
17//! Test: this module's unit tests.
18
19use serde_json::{Value, json};
20use trusty_common::mcp::error_codes;
21
22/// A JSON-RPC 2.0 error, as returned by a method handler.
23///
24/// Why: mirrors `trusty_common::mcp::JsonRpcError`'s shape so the router can
25/// convert one into the other with a straight field copy, but stays a
26/// separate type so handler code never has to construct the wire envelope
27/// directly.
28/// What: `code` is a JSON-RPC error code (spec-defined or application
29/// range); `message` is human-readable; `data` is optional structured detail
30/// attached to the wire error.
31/// Test: `rpc_error_invalid_params_sets_code`, `rpc_error_internal_sets_code`.
32#[derive(Debug, Clone)]
33pub struct RpcError {
34    pub code: i32,
35    pub message: String,
36    pub data: Option<Value>,
37}
38
39impl RpcError {
40    /// Construct an `RpcError` with an arbitrary code.
41    ///
42    /// Why: escape hatch for application-defined codes outside the standard
43    /// JSON-RPC range (e.g. a future domain-specific error).
44    /// What: sets `code`/`message`, leaves `data` unset.
45    /// Test: `rpc_error_new_has_no_data_by_default`.
46    pub fn new(code: i32, message: impl Into<String>) -> Self {
47        Self {
48            code,
49            message: message.into(),
50            data: None,
51        }
52    }
53
54    /// Attach structured `data` to an existing error.
55    ///
56    /// Why: some failures carry machine-readable detail (e.g. which field
57    /// failed validation) beyond the human-readable `message`.
58    /// What: builder-style setter; returns `self` for chaining.
59    /// Test: `rpc_error_with_data_attaches_payload`.
60    pub fn with_data(mut self, data: Value) -> Self {
61        self.data = Some(data);
62        self
63    }
64
65    /// Build a `-32602 Invalid params` error.
66    ///
67    /// Why: the standard code a handler returns when it cannot parse or
68    /// validate its `params` argument.
69    /// What: `code = error_codes::INVALID_PARAMS`.
70    /// Test: `rpc_error_invalid_params_sets_code`.
71    pub fn invalid_params(message: impl Into<String>) -> Self {
72        Self::new(error_codes::INVALID_PARAMS, message)
73    }
74
75    /// Build a `-32603 Internal error` error.
76    ///
77    /// Why: the standard code for a handler-side failure that isn't the
78    /// caller's fault (I/O failure, downstream panic-free error, etc.).
79    /// What: `code = error_codes::INTERNAL_ERROR`.
80    /// Test: `rpc_error_internal_sets_code`.
81    pub fn internal(message: impl Into<String>) -> Self {
82        Self::new(error_codes::INTERNAL_ERROR, message)
83    }
84
85    /// Build a domain-taxonomy error (vision spec §13.2): a code from the
86    /// spec's table plus a stable `error_type` string tagged onto `data`.
87    ///
88    /// Why: the spec's domain errors (`session_not_found`, `invalid_argument`,
89    /// `cancelled`, …) live in a numeric range distinct from the standard
90    /// JSON-RPC `-326xx` codes, and every one of them carries
91    /// `data.error_type` so a client can match on the string rather than
92    /// memorising numbers. Centralising the shape here means every domain
93    /// error is built the same way.
94    /// What: sets `code`, `message`, and `data = {"error_type": error_type}`.
95    /// Test: `rpc_error_domain_sets_error_type_in_data`.
96    fn domain(code: i32, error_type: &'static str, message: impl Into<String>) -> Self {
97        Self::new(code, message).with_data(json!({"error_type": error_type}))
98    }
99
100    /// Build a `-32007 session_not_found` error (vision spec §13.2).
101    ///
102    /// Why: the specific, spec-named code for "the session id in `params`
103    /// does not exist in the registry" — used by every `session.*` method
104    /// that takes a `session_id`.
105    /// What: `message` embeds `session_id` for operator-visible logs;
106    /// `data.error_type = "session_not_found"`.
107    /// Test: `rpc_error_session_not_found_sets_code_and_type`.
108    pub fn session_not_found(session_id: &str) -> Self {
109        Self::domain(
110            -32007,
111            "session_not_found",
112            format!("session not found: {session_id}"),
113        )
114    }
115
116    /// Build a `-32003 invalid_argument` error (vision spec §13.2).
117    ///
118    /// Why: the spec's domain-level "malformed request" code, distinct from
119    /// the JSON-RPC protocol-level `-32602 Invalid params` — used when a
120    /// method's arguments parse as JSON but fail a semantic check (e.g. an
121    /// empty task description).
122    /// What: `data.error_type = "invalid_argument"`.
123    /// Test: `rpc_error_invalid_argument_sets_code_and_type`.
124    pub fn invalid_argument(message: impl Into<String>) -> Self {
125        Self::domain(-32003, "invalid_argument", message)
126    }
127}
128
129impl std::fmt::Display for RpcError {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        write!(f, "JSON-RPC error {}: {}", self.code, self.message)
132    }
133}
134
135impl std::error::Error for RpcError {}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140    use serde_json::json;
141
142    /// `invalid_params` must use the spec's `-32602` code.
143    #[test]
144    fn rpc_error_invalid_params_sets_code() {
145        let e = RpcError::invalid_params("bad shape");
146        assert_eq!(e.code, error_codes::INVALID_PARAMS);
147        assert_eq!(e.message, "bad shape");
148        assert!(e.data.is_none());
149    }
150
151    /// `internal` must use the spec's `-32603` code.
152    #[test]
153    fn rpc_error_internal_sets_code() {
154        let e = RpcError::internal("boom");
155        assert_eq!(e.code, error_codes::INTERNAL_ERROR);
156        assert_eq!(e.message, "boom");
157    }
158
159    /// `new` alone must not attach any `data`.
160    #[test]
161    fn rpc_error_new_has_no_data_by_default() {
162        let e = RpcError::new(-1, "custom");
163        assert_eq!(e.code, -1);
164        assert!(e.data.is_none());
165    }
166
167    /// `with_data` must attach the supplied payload.
168    #[test]
169    fn rpc_error_with_data_attaches_payload() {
170        let e = RpcError::invalid_params("bad field").with_data(json!({"field": "name"}));
171        assert_eq!(e.data, Some(json!({"field": "name"})));
172    }
173
174    /// `Display` must surface both the code and the message for logs.
175    #[test]
176    fn rpc_error_display_contains_code_and_message() {
177        let e = RpcError::internal("db unreachable");
178        let s = e.to_string();
179        assert!(s.contains("-32603"));
180        assert!(s.contains("db unreachable"));
181    }
182
183    /// `session_not_found` must use the spec's `-32007` code, embed the id
184    /// in the message, and tag `error_type` in `data`.
185    #[test]
186    fn rpc_error_session_not_found_sets_code_and_type() {
187        let e = RpcError::session_not_found("s-123");
188        assert_eq!(e.code, -32007);
189        assert!(e.message.contains("s-123"));
190        assert_eq!(e.data, Some(json!({"error_type": "session_not_found"})));
191    }
192
193    /// `invalid_argument` must use the spec's `-32003` code and tag
194    /// `error_type` in `data`.
195    #[test]
196    fn rpc_error_invalid_argument_sets_code_and_type() {
197        let e = RpcError::invalid_argument("task must not be empty");
198        assert_eq!(e.code, -32003);
199        assert_eq!(e.data, Some(json!({"error_type": "invalid_argument"})));
200    }
201}