1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use std::error;
use std::result;
use std::fmt;
use std::string::ToString;
use serde_json::Value;
#[derive(Clone, PartialEq, Debug)]
pub enum ErrorCode {
ParseError,
InvalidRequest,
MethodNotFound,
InvalidParams,
InternalError,
ServerError(i64),
}
impl ErrorCode {
pub fn code(&self) -> i64 {
match *self {
ErrorCode::ParseError => -32700,
ErrorCode::InvalidRequest => -32600,
ErrorCode::MethodNotFound => -32601,
ErrorCode::InvalidParams => -32602,
ErrorCode::InternalError => -32603,
ErrorCode::ServerError(code) => code,
}
}
pub fn as_str(&self) -> &'static str {
match *self {
ErrorCode::ParseError => "Parse error",
ErrorCode::InvalidRequest => "Invalid request",
ErrorCode::MethodNotFound => "Method not found",
ErrorCode::InvalidParams => "Invalid params",
ErrorCode::InternalError => "Internal error",
ErrorCode::ServerError(_) => "Server error",
}
}
}
impl ToString for ErrorCode {
fn to_string(&self) -> String {
String::from(self.as_str())
}
}
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
pub struct Error {
pub code: i64,
pub message: String,
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
impl Error {
pub fn new(code: ErrorCode) -> Self {
Error {
code: code.code(),
message: code.to_string(),
data: None,
}
}
pub fn parse_error() -> Self {
Self::new(ErrorCode::ParseError)
}
pub fn invalid_request() -> Self {
Self::new(ErrorCode::InvalidRequest)
}
pub fn method_not_found() -> Self {
Self::new(ErrorCode::MethodNotFound)
}
pub fn invalid_params() -> Self {
Self::new(ErrorCode::InvalidParams)
}
pub fn internal_error() -> Self {
Self::new(ErrorCode::InternalError)
}
}
impl error::Error for Error {
fn description(&self) -> &str {
&self.message
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&::serde_json::to_string(&self).unwrap(), f)
}
}
pub type Result<T> = result::Result<T, Error>;