vv_agent/app_server/protocol/
errors.rs1use serde_json::Value;
2
3use super::jsonrpc::{JsonRpcError, JsonRpcErrorBody, RequestId};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum AppServerErrorCode {
7 ServerOverloaded,
8 InvalidRequest,
9 MethodNotFound,
10 InvalidParams,
11 InternalError,
12 NotInitialized,
13 AlreadyInitialized,
14 ExperimentalApiRequired,
15 UnsupportedMethod,
16}
17
18impl AppServerErrorCode {
19 pub fn code(self) -> i64 {
20 match self {
21 Self::ServerOverloaded => -32001,
22 Self::InvalidRequest => -32600,
23 Self::MethodNotFound => -32601,
24 Self::InvalidParams => -32602,
25 Self::InternalError => -32603,
26 Self::NotInitialized => -32010,
27 Self::AlreadyInitialized => -32011,
28 Self::ExperimentalApiRequired => -32012,
29 Self::UnsupportedMethod => -32013,
30 }
31 }
32}
33
34#[derive(Debug, Clone, PartialEq)]
35pub struct AppServerError {
36 code: AppServerErrorCode,
37 message: String,
38 data: Option<Value>,
39}
40
41impl AppServerError {
42 pub fn new(code: AppServerErrorCode, message: impl Into<String>) -> Self {
43 Self {
44 code,
45 message: message.into(),
46 data: None,
47 }
48 }
49
50 pub fn invalid_params(message: impl Into<String>) -> Self {
51 Self::new(AppServerErrorCode::InvalidParams, message)
52 }
53
54 pub fn invalid_request(message: impl Into<String>) -> Self {
55 Self::new(AppServerErrorCode::InvalidRequest, message)
56 }
57
58 pub fn internal(message: impl Into<String>) -> Self {
59 Self::new(AppServerErrorCode::InternalError, message)
60 }
61
62 pub fn not_initialized() -> Self {
63 Self::new(AppServerErrorCode::NotInitialized, "Not initialized")
64 }
65
66 pub fn already_initialized() -> Self {
67 Self::new(
68 AppServerErrorCode::AlreadyInitialized,
69 "Already initialized",
70 )
71 }
72
73 pub fn server_overloaded() -> Self {
74 Self::new(
75 AppServerErrorCode::ServerOverloaded,
76 "Server overloaded; retry later.",
77 )
78 }
79
80 pub fn unsupported_method(method: impl Into<String>) -> Self {
81 let method = method.into();
82 Self::new(
83 AppServerErrorCode::UnsupportedMethod,
84 format!("Unsupported App Server method: {method}"),
85 )
86 .with_data(serde_json::json!({ "method": method }))
87 }
88
89 pub fn with_data(mut self, data: Value) -> Self {
90 self.data = Some(data);
91 self
92 }
93
94 pub fn code(&self) -> AppServerErrorCode {
95 self.code
96 }
97
98 pub fn message(&self) -> &str {
99 &self.message
100 }
101
102 pub fn into_json_rpc_error(self, id: RequestId) -> JsonRpcError {
103 JsonRpcError {
104 id,
105 error: JsonRpcErrorBody {
106 code: self.code.code(),
107 message: self.message,
108 data: self.data,
109 },
110 }
111 }
112}