agent_client_protocol/
error.rs

1use std::{fmt::Display, ops::Deref as _};
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
7pub struct Error {
8    pub code: i32,
9    pub message: String,
10    #[serde(skip_serializing_if = "Option::is_none")]
11    pub data: Option<serde_json::Value>,
12}
13
14impl Error {
15    pub fn new(code: impl Into<(i32, String)>) -> Self {
16        let (code, message) = code.into();
17        Error {
18            code,
19            message,
20            data: None,
21        }
22    }
23
24    pub fn with_data(mut self, data: impl Into<serde_json::Value>) -> Self {
25        self.data = Some(data.into());
26        self
27    }
28
29    /// Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
30    pub fn parse_error() -> Self {
31        Error::new(ErrorCode::PARSE_ERROR)
32    }
33
34    /// The JSON sent is not a valid Request object.
35    pub fn invalid_request() -> Self {
36        Error::new(ErrorCode::INVALID_REQUEST)
37    }
38
39    /// The method does not exist / is not available.
40    pub fn method_not_found() -> Self {
41        Error::new(ErrorCode::METHOD_NOT_FOUND)
42    }
43
44    /// Invalid method parameter(s).
45    pub fn invalid_params() -> Self {
46        Error::new(ErrorCode::INVALID_PARAMS)
47    }
48
49    /// Internal JSON-RPC error.
50    pub fn internal_error() -> Self {
51        Error::new(ErrorCode::INTERNAL_ERROR)
52    }
53
54    /// Authentication required.
55    pub fn auth_required() -> Self {
56        Error::new(ErrorCode::AUTH_REQUIRED)
57    }
58
59    pub fn into_internal_error(err: impl std::error::Error) -> Self {
60        Error::internal_error().with_data(err.to_string())
61    }
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
65pub struct ErrorCode {
66    pub code: i32,
67    pub message: &'static str,
68}
69
70impl ErrorCode {
71    pub const PARSE_ERROR: ErrorCode = ErrorCode {
72        code: -32700,
73        message: "Parse error",
74    };
75
76    pub const INVALID_REQUEST: ErrorCode = ErrorCode {
77        code: -32600,
78        message: "Invalid Request",
79    };
80
81    pub const METHOD_NOT_FOUND: ErrorCode = ErrorCode {
82        code: -32601,
83        message: "Method not found",
84    };
85
86    pub const INVALID_PARAMS: ErrorCode = ErrorCode {
87        code: -32602,
88        message: "Invalid params",
89    };
90
91    pub const INTERNAL_ERROR: ErrorCode = ErrorCode {
92        code: -32603,
93        message: "Internal error",
94    };
95
96    pub const AUTH_REQUIRED: ErrorCode = ErrorCode {
97        code: -32000,
98        message: "Authentication required",
99    };
100}
101
102impl From<ErrorCode> for (i32, String) {
103    fn from(error_code: ErrorCode) -> Self {
104        (error_code.code, error_code.message.to_string())
105    }
106}
107
108impl From<ErrorCode> for Error {
109    fn from(error_code: ErrorCode) -> Self {
110        Error::new(error_code)
111    }
112}
113
114impl std::error::Error for Error {}
115
116impl Display for Error {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        if self.message.is_empty() {
119            write!(f, "{}", self.code)?;
120        } else {
121            write!(f, "{}", self.message)?;
122        }
123
124        if let Some(data) = &self.data {
125            write!(f, ": {data}")?;
126        }
127
128        Ok(())
129    }
130}
131
132impl From<anyhow::Error> for Error {
133    fn from(error: anyhow::Error) -> Self {
134        Error::into_internal_error(error.deref())
135    }
136}
137
138impl From<serde_json::Error> for Error {
139    fn from(error: serde_json::Error) -> Self {
140        Error::invalid_params().with_data(error.to_string())
141    }
142}