use serde_json::{Value, json};
use trusty_common::mcp::error_codes;
#[derive(Debug, Clone)]
pub struct RpcError {
pub code: i32,
pub message: String,
pub data: Option<Value>,
}
impl RpcError {
pub fn new(code: i32, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
data: None,
}
}
pub fn with_data(mut self, data: Value) -> Self {
self.data = Some(data);
self
}
pub fn invalid_params(message: impl Into<String>) -> Self {
Self::new(error_codes::INVALID_PARAMS, message)
}
pub fn internal(message: impl Into<String>) -> Self {
Self::new(error_codes::INTERNAL_ERROR, message)
}
fn domain(code: i32, error_type: &'static str, message: impl Into<String>) -> Self {
Self::new(code, message).with_data(json!({"error_type": error_type}))
}
pub fn session_not_found(session_id: &str) -> Self {
Self::domain(
-32007,
"session_not_found",
format!("session not found: {session_id}"),
)
}
pub fn invalid_argument(message: impl Into<String>) -> Self {
Self::domain(-32003, "invalid_argument", message)
}
}
impl std::fmt::Display for RpcError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "JSON-RPC error {}: {}", self.code, self.message)
}
}
impl std::error::Error for RpcError {}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn rpc_error_invalid_params_sets_code() {
let e = RpcError::invalid_params("bad shape");
assert_eq!(e.code, error_codes::INVALID_PARAMS);
assert_eq!(e.message, "bad shape");
assert!(e.data.is_none());
}
#[test]
fn rpc_error_internal_sets_code() {
let e = RpcError::internal("boom");
assert_eq!(e.code, error_codes::INTERNAL_ERROR);
assert_eq!(e.message, "boom");
}
#[test]
fn rpc_error_new_has_no_data_by_default() {
let e = RpcError::new(-1, "custom");
assert_eq!(e.code, -1);
assert!(e.data.is_none());
}
#[test]
fn rpc_error_with_data_attaches_payload() {
let e = RpcError::invalid_params("bad field").with_data(json!({"field": "name"}));
assert_eq!(e.data, Some(json!({"field": "name"})));
}
#[test]
fn rpc_error_display_contains_code_and_message() {
let e = RpcError::internal("db unreachable");
let s = e.to_string();
assert!(s.contains("-32603"));
assert!(s.contains("db unreachable"));
}
#[test]
fn rpc_error_session_not_found_sets_code_and_type() {
let e = RpcError::session_not_found("s-123");
assert_eq!(e.code, -32007);
assert!(e.message.contains("s-123"));
assert_eq!(e.data, Some(json!({"error_type": "session_not_found"})));
}
#[test]
fn rpc_error_invalid_argument_sets_code_and_type() {
let e = RpcError::invalid_argument("task must not be empty");
assert_eq!(e.code, -32003);
assert_eq!(e.data, Some(json!({"error_type": "invalid_argument"})));
}
}