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    pub fn into_internal_error(err: impl std::error::Error) -> Self {
55        Error::internal_error().with_data(err.to_string())
56    }
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
60pub struct ErrorCode {
61    code: i32,
62    message: &'static str,
63}
64
65impl ErrorCode {
66    pub const PARSE_ERROR: ErrorCode = ErrorCode {
67        code: -32700,
68        message: "Parse error",
69    };
70
71    pub const INVALID_REQUEST: ErrorCode = ErrorCode {
72        code: -32600,
73        message: "Invalid Request",
74    };
75
76    pub const METHOD_NOT_FOUND: ErrorCode = ErrorCode {
77        code: -32601,
78        message: "Method not found",
79    };
80
81    pub const INVALID_PARAMS: ErrorCode = ErrorCode {
82        code: -32602,
83        message: "Invalid params",
84    };
85
86    pub const INTERNAL_ERROR: ErrorCode = ErrorCode {
87        code: -32603,
88        message: "Internal error",
89    };
90}
91
92impl From<ErrorCode> for (i32, String) {
93    fn from(error_code: ErrorCode) -> Self {
94        (error_code.code, error_code.message.to_string())
95    }
96}
97
98impl From<ErrorCode> for Error {
99    fn from(error_code: ErrorCode) -> Self {
100        Error::new(error_code)
101    }
102}
103
104impl std::error::Error for Error {}
105
106impl Display for Error {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        if self.message.is_empty() {
109            write!(f, "{}", self.code)?;
110        } else {
111            write!(f, "{}", self.message)?;
112        }
113
114        if let Some(data) = &self.data {
115            write!(f, ": {data}")?;
116        }
117
118        Ok(())
119    }
120}
121
122impl From<anyhow::Error> for Error {
123    fn from(error: anyhow::Error) -> Self {
124        Error::into_internal_error(error.deref())
125    }
126}
127
128impl From<serde_json::Error> for Error {
129    fn from(error: serde_json::Error) -> Self {
130        Error::invalid_params().with_data(error.to_string())
131    }
132}