tower_lsp/jsonrpc/
error.rs

1//! Error types defined by the JSON-RPC specification.
2
3use std::fmt::{self, Display, Formatter};
4
5use serde::de::Deserializer;
6use serde::ser::Serializer;
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10/// A list of numeric error codes used in JSON-RPC responses.
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum ErrorCode {
13    /// Invalid JSON was received by the server.
14    ParseError,
15    /// The JSON sent is not a valid Request object.
16    InvalidRequest,
17    /// The method does not exist / is not available.
18    MethodNotFound,
19    /// Invalid method parameter(s).
20    InvalidParams,
21    /// Internal JSON-RPC error.
22    InternalError,
23    /// Reserved for implementation-defined server errors.
24    ServerError(i64),
25
26    /// The request was cancelled by the client.
27    ///
28    /// # Compatibility
29    ///
30    /// This error code is defined by the Language Server Protocol.
31    RequestCancelled,
32    /// The request was invalidated by another incoming request.
33    ///
34    /// # Compatibility
35    ///
36    /// This error code is specific to the Language Server Protocol.
37    ContentModified,
38}
39
40impl ErrorCode {
41    /// Returns the integer error code value.
42    #[inline]
43    pub fn code(&self) -> i64 {
44        match *self {
45            ErrorCode::ParseError => -32700,
46            ErrorCode::InvalidRequest => -32600,
47            ErrorCode::MethodNotFound => -32601,
48            ErrorCode::InvalidParams => -32602,
49            ErrorCode::InternalError => -32603,
50            ErrorCode::RequestCancelled => -32800,
51            ErrorCode::ContentModified => -32801,
52            ErrorCode::ServerError(code) => code,
53        }
54    }
55
56    /// Returns a human-readable description of the error.
57    #[inline]
58    pub fn description(&self) -> &'static str {
59        match *self {
60            ErrorCode::ParseError => "Parse error",
61            ErrorCode::InvalidRequest => "Invalid request",
62            ErrorCode::MethodNotFound => "Method not found",
63            ErrorCode::InvalidParams => "Invalid params",
64            ErrorCode::InternalError => "Internal error",
65            ErrorCode::RequestCancelled => "Canceled",
66            ErrorCode::ContentModified => "Content modified",
67            ErrorCode::ServerError(_) => "Server error",
68        }
69    }
70}
71
72impl From<i64> for ErrorCode {
73    #[inline]
74    fn from(code: i64) -> Self {
75        match code {
76            -32700 => ErrorCode::ParseError,
77            -32600 => ErrorCode::InvalidRequest,
78            -32601 => ErrorCode::MethodNotFound,
79            -32602 => ErrorCode::InvalidParams,
80            -32603 => ErrorCode::InternalError,
81            -32800 => ErrorCode::RequestCancelled,
82            -32801 => ErrorCode::ContentModified,
83            code => ErrorCode::ServerError(code),
84        }
85    }
86}
87
88impl Display for ErrorCode {
89    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
90        Display::fmt(&self.code(), f)
91    }
92}
93
94impl<'a> Deserialize<'a> for ErrorCode {
95    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
96    where
97        D: Deserializer<'a>,
98    {
99        let code: i64 = Deserialize::deserialize(deserializer)?;
100        Ok(ErrorCode::from(code))
101    }
102}
103
104impl Serialize for ErrorCode {
105    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
106    where
107        S: Serializer,
108    {
109        self.code().serialize(serializer)
110    }
111}
112
113/// A JSON-RPC error object.
114#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
115#[serde(deny_unknown_fields)]
116pub struct Error {
117    /// A number indicating the error type that occurred.
118    pub code: ErrorCode,
119    /// A short description of the error.
120    pub message: String,
121    /// Additional information about the error, if any.
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub data: Option<Value>,
124}
125
126impl Error {
127    /// Creates a new error from the given `ErrorCode`.
128    #[inline]
129    pub fn new(code: ErrorCode) -> Self {
130        Error {
131            code,
132            message: code.description().to_string(),
133            data: None,
134        }
135    }
136
137    /// Creates a new parse error (`-32700`).
138    #[inline]
139    pub fn parse_error() -> Self {
140        Error::new(ErrorCode::ParseError)
141    }
142
143    /// Creates a new "invalid request" error (`-32600`).
144    #[inline]
145    pub fn invalid_request() -> Self {
146        Error::new(ErrorCode::InvalidRequest)
147    }
148
149    /// Creates a new "method not found" error (`-32601`).
150    #[inline]
151    pub fn method_not_found() -> Self {
152        Error::new(ErrorCode::MethodNotFound)
153    }
154
155    /// Creates a new "invalid params" error (`-32602`).
156    #[inline]
157    pub fn invalid_params<M>(message: M) -> Self
158    where
159        M: Into<String>,
160    {
161        Error {
162            code: ErrorCode::InvalidParams,
163            message: message.into(),
164            data: None,
165        }
166    }
167
168    /// Creates a new internal error (`-32603`).
169    #[inline]
170    pub fn internal_error() -> Self {
171        Error::new(ErrorCode::InternalError)
172    }
173
174    /// Creates a new "request cancelled" error (`-32800`).
175    ///
176    /// # Compatibility
177    ///
178    /// This error code is defined by the Language Server Protocol.
179    #[inline]
180    pub fn request_cancelled() -> Self {
181        Error::new(ErrorCode::RequestCancelled)
182    }
183
184    /// Creates a new "content modified" error (`-32801`).
185    ///
186    /// # Compatibility
187    ///
188    /// This error code is defined by the Language Server Protocol.
189    #[inline]
190    pub fn content_modified() -> Self {
191        Error::new(ErrorCode::ContentModified)
192    }
193}
194
195impl Display for Error {
196    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
197        write!(f, "{}: {}", self.code.description(), self.message)
198    }
199}
200
201impl std::error::Error for Error {}