Skip to main content

lsp_lang/
response.rs

1//! [`ResponseError`]: the failed outcome of a request.
2
3use std::fmt;
4
5use jsonx_lib::Value;
6use rpc_io::{ErrorCode, ErrorObject};
7
8use crate::error::Error;
9
10/// A JSON-RPC error: the failed outcome of a request, sent back to the client
11/// in place of a result.
12///
13/// A handler returns one to refuse or fail a request; the server also sends
14/// them itself for protocol violations (a request before `initialize`, an
15/// unknown method, malformed JSON). The associated constants are the codes
16/// JSON-RPC and the protocol define; pick the one that tells the client what to
17/// do next. For instance [`CONTENT_MODIFIED`](ResponseError::CONTENT_MODIFIED)
18/// asks it to retry against the newer text, while
19/// [`REQUEST_FAILED`](ResponseError::REQUEST_FAILED) says the request was
20/// understood but could not be served.
21///
22/// # Examples
23///
24/// ```
25/// use lsp_lang::ResponseError;
26///
27/// let err = ResponseError::new(ResponseError::REQUEST_FAILED, "no project loaded");
28/// assert_eq!(err.code(), -32803);
29/// assert_eq!(err.message(), "no project loaded");
30/// assert_eq!(err.to_string(), "no project loaded (code -32803)");
31/// ```
32#[derive(Clone, Debug, PartialEq)]
33pub struct ResponseError {
34    code: i32,
35    message: String,
36    data: Option<Value<'static>>,
37}
38
39impl ResponseError {
40    /// Invalid JSON was received. Sent by the server; a handler never sees it.
41    pub const PARSE_ERROR: i32 = -32700;
42    /// The message is not a valid request object.
43    pub const INVALID_REQUEST: i32 = -32600;
44    /// The method does not exist or is not supported. The default answer of
45    /// the [`Handler`](crate::Handler) methods a language does not implement.
46    pub const METHOD_NOT_FOUND: i32 = -32601;
47    /// The parameters are invalid. What the `from_json` conversions return on
48    /// a mismatch.
49    pub const INVALID_PARAMS: i32 = -32602;
50    /// An internal error, such as a result that failed to serialize.
51    pub const INTERNAL_ERROR: i32 = -32603;
52    /// A request arrived before `initialize`. Sent by the server.
53    pub const SERVER_NOT_INITIALIZED: i32 = -32002;
54    /// The request was understood but failed; the message says why.
55    pub const REQUEST_FAILED: i32 = -32803;
56    /// The server cancelled the request; the client may retry it.
57    pub const SERVER_CANCELLED: i32 = -32802;
58    /// The document changed while the request was served, so its result would
59    /// be stale; the client should retry against the new content.
60    pub const CONTENT_MODIFIED: i32 = -32801;
61    /// The client cancelled the request (`$/cancelRequest`).
62    pub const REQUEST_CANCELLED: i32 = -32800;
63
64    /// Builds an error with `code` and a human-readable `message`.
65    ///
66    /// The message is shown to the user by some clients; say what failed and,
67    /// where it helps, what to do about it.
68    ///
69    /// # Examples
70    ///
71    /// ```
72    /// use lsp_lang::ResponseError;
73    ///
74    /// let err = ResponseError::new(ResponseError::INVALID_PARAMS, "position is outside the document");
75    /// assert_eq!(err.code(), ResponseError::INVALID_PARAMS);
76    /// ```
77    #[must_use]
78    pub fn new(code: i32, message: impl Into<String>) -> Self {
79        Self {
80            code,
81            message: message.into(),
82            data: None,
83        }
84    }
85
86    /// Attaches structured details (`error.data`) for clients that act on
87    /// them.
88    ///
89    /// # Examples
90    ///
91    /// ```
92    /// use lsp_lang::{json, ResponseError};
93    ///
94    /// let err = ResponseError::new(ResponseError::REQUEST_FAILED, "stale")
95    ///     .with_data(json!({ "expected": 4 }));
96    /// assert_eq!(err.data().and_then(|d| d["expected"].as_i64()), Some(4));
97    /// ```
98    #[must_use]
99    pub fn with_data(mut self, data: Value<'static>) -> Self {
100        self.data = Some(data);
101        self
102    }
103
104    /// Returns the error code.
105    ///
106    /// # Examples
107    ///
108    /// ```
109    /// use lsp_lang::ResponseError;
110    ///
111    /// assert_eq!(ResponseError::new(-1, "x").code(), -1);
112    /// ```
113    #[inline]
114    #[must_use]
115    pub const fn code(&self) -> i32 {
116        self.code
117    }
118
119    /// Returns the message.
120    ///
121    /// # Examples
122    ///
123    /// ```
124    /// use lsp_lang::ResponseError;
125    ///
126    /// assert_eq!(ResponseError::new(-1, "boom").message(), "boom");
127    /// ```
128    #[inline]
129    #[must_use]
130    pub fn message(&self) -> &str {
131        &self.message
132    }
133
134    /// Returns the structured details, if any were attached or received.
135    ///
136    /// # Examples
137    ///
138    /// ```
139    /// use lsp_lang::ResponseError;
140    ///
141    /// assert!(ResponseError::new(-1, "boom").data().is_none());
142    /// ```
143    #[inline]
144    #[must_use]
145    pub fn data(&self) -> Option<&Value<'static>> {
146        self.data.as_ref()
147    }
148
149    /// An `INVALID_PARAMS` error: the shape of a request's parameters was
150    /// wrong.
151    pub(crate) fn invalid_params(message: impl Into<String>) -> Self {
152        Self::new(Self::INVALID_PARAMS, message)
153    }
154
155    /// A `METHOD_NOT_FOUND` error for `what` (a method or a feature).
156    pub(crate) fn unsupported(what: &str) -> Self {
157        Self::new(Self::METHOD_NOT_FOUND, format!("unhandled method `{what}`"))
158    }
159}
160
161impl fmt::Display for ResponseError {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        write!(f, "{} (code {})", self.message, self.code)
164    }
165}
166
167impl std::error::Error for ResponseError {}
168
169impl From<Error> for ResponseError {
170    /// Turns a library error met while serving a request, in practice a send
171    /// that failed, into an [`INTERNAL_ERROR`](ResponseError::INTERNAL_ERROR)
172    /// response.
173    fn from(error: Error) -> Self {
174        Self::new(Self::INTERNAL_ERROR, error.to_string())
175    }
176}
177
178impl From<jsonx_lib::Error> for ResponseError {
179    /// A JSON error met while reading a request's parameters becomes an
180    /// [`INVALID_PARAMS`](ResponseError::INVALID_PARAMS) response.
181    fn from(error: jsonx_lib::Error) -> Self {
182        Self::new(Self::INVALID_PARAMS, format!("invalid params: {error}"))
183    }
184}
185
186impl From<ErrorObject> for ResponseError {
187    /// Reads the transport's error object: a code outside `i32` reads as
188    /// `INTERNAL_ERROR`, and `data` that does not parse is dropped.
189    fn from(error: ErrorObject) -> Self {
190        let code = i32::try_from(error.code().0).unwrap_or(Self::INTERNAL_ERROR);
191        let mut out = Self::new(code, error.message());
192        out.data = error
193            .data()
194            .and_then(|raw| raw.parse().ok())
195            .map(Value::into_owned);
196        out
197    }
198}
199
200impl From<ResponseError> for ErrorObject {
201    fn from(error: ResponseError) -> Self {
202        let mut out = ErrorObject::new(ErrorCode(i64::from(error.code)), error.message);
203        if let Some(data) = error.data {
204            out = out.with_data(data);
205        }
206        out
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use jsonx_lib::json;
213
214    use super::*;
215
216    #[test]
217    fn test_response_error_from_error_is_internal() {
218        let err = ResponseError::from(Error::Disconnected);
219        assert_eq!(err.code(), ResponseError::INTERNAL_ERROR);
220        assert!(!err.message().is_empty());
221    }
222
223    #[test]
224    fn test_response_error_round_trips_through_the_transport_object() {
225        let err = ResponseError::new(-32803, "stale").with_data(json!({ "n": 1 }));
226        let object = ErrorObject::from(err.clone());
227        assert_eq!(object.code(), ErrorCode(-32803));
228        assert_eq!(ResponseError::from(object), err);
229    }
230
231    #[test]
232    fn test_response_error_from_huge_code_is_internal() {
233        let object = ErrorObject::new(ErrorCode(i64::MAX), "big");
234        assert_eq!(
235            ResponseError::from(object).code(),
236            ResponseError::INTERNAL_ERROR
237        );
238    }
239
240    #[test]
241    fn test_response_error_from_json_error_is_invalid_params() {
242        let err = jsonx_lib::parse("[").err().map(ResponseError::from);
243        assert_eq!(err.map(|e| e.code()), Some(ResponseError::INVALID_PARAMS));
244    }
245}