Skip to main content

rpc_io/
error_object.rs

1//! [`ErrorObject`] and [`ErrorCode`]: the `error` member of a response.
2
3use alloc::{borrow::Cow, format, string::String};
4use core::fmt;
5
6use crate::{
7    raw::{Json, Raw},
8    text,
9};
10
11/// A JSON-RPC error code.
12///
13/// The constants are the five codes JSON-RPC 2.0 defines, plus three the
14/// crate itself answers with. Any integer is a valid code; protocols define
15/// their own (LSP's `ContentModified` is `-32801`, LexerSketch's "stale
16/// version" is `1001`), and a peer's code is passed through as it was sent.
17///
18/// # Examples
19///
20/// ```
21/// use rpc_io::ErrorCode;
22///
23/// assert_eq!(ErrorCode::METHOD_NOT_FOUND.0, -32601);
24/// assert_eq!(ErrorCode::METHOD_NOT_FOUND.name(), Some("method not found"));
25/// assert_eq!(ErrorCode(1001).name(), None);
26/// assert_eq!(ErrorCode::INVALID_PARAMS.to_string(), "-32602 (invalid params)");
27/// ```
28#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
29pub struct ErrorCode(pub i64);
30
31impl ErrorCode {
32    /// `-32700`: the message is not valid JSON.
33    pub const PARSE_ERROR: ErrorCode = ErrorCode(-32700);
34    /// `-32600`: the message is JSON but not a valid request object.
35    pub const INVALID_REQUEST: ErrorCode = ErrorCode(-32600);
36    /// `-32601`: no handler is registered for the method.
37    pub const METHOD_NOT_FOUND: ErrorCode = ErrorCode(-32601);
38    /// `-32602`: the params are not what the method takes.
39    pub const INVALID_PARAMS: ErrorCode = ErrorCode(-32602);
40    /// `-32603`: the server failed, for example a handler panicked.
41    pub const INTERNAL_ERROR: ErrorCode = ErrorCode(-32603);
42    /// `-32000`: too many requests are already being answered. The first code
43    /// of the range JSON-RPC 2.0 reserves for implementation-defined server
44    /// errors.
45    pub const SERVER_OVERLOADED: ErrorCode = ErrorCode(-32000);
46    /// `-32002`: a request arrived before the protocol's opening request
47    /// succeeded (LSP's `ServerNotInitialized`); see
48    /// [`Gate`](crate::Gate).
49    pub const SERVER_NOT_INITIALIZED: ErrorCode = ErrorCode(-32002);
50    /// `-32800`: the request was cancelled by its sender (LSP's
51    /// `RequestCancelled`); see [`Cancellation`](crate::Cancellation).
52    pub const REQUEST_CANCELLED: ErrorCode = ErrorCode(-32800);
53
54    /// A short name for the codes this crate defines, `None` for others.
55    ///
56    /// # Examples
57    ///
58    /// ```
59    /// assert_eq!(rpc_io::ErrorCode::PARSE_ERROR.name(), Some("parse error"));
60    /// ```
61    #[must_use]
62    pub const fn name(self) -> Option<&'static str> {
63        Some(match self.0 {
64            -32700 => "parse error",
65            -32600 => "invalid request",
66            -32601 => "method not found",
67            -32602 => "invalid params",
68            -32603 => "internal error",
69            -32000 => "server overloaded",
70            -32002 => "server not initialized",
71            -32800 => "request cancelled",
72            _ => return None,
73        })
74    }
75
76    /// Whether the code lies in `-32768..=-32000`, the range JSON-RPC 2.0
77    /// reserves for predefined and implementation-defined errors.
78    ///
79    /// # Examples
80    ///
81    /// ```
82    /// use rpc_io::ErrorCode;
83    ///
84    /// assert!(ErrorCode::INTERNAL_ERROR.is_reserved());
85    /// assert!(!ErrorCode(1001).is_reserved());
86    /// ```
87    #[must_use]
88    pub const fn is_reserved(self) -> bool {
89        self.0 >= -32768 && self.0 <= -32000
90    }
91}
92
93impl fmt::Display for ErrorCode {
94    /// The number, with the name when the code has one.
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        match self.name() {
97            Some(name) => write!(f, "{} ({name})", self.0),
98            None => write!(f, "{}", self.0),
99        }
100    }
101}
102
103/// The `error` member of a response: a code, a message, and optional data.
104///
105/// Handlers return one to fail a request; the crate builds one for every
106/// protocol error it answers itself; and a peer's error response arrives as
107/// one. The message is kept owned (it is short, and an error usually outlives
108/// the message it was read from); `data` is any JSON value, kept as text.
109///
110/// # Examples
111///
112/// ```
113/// use jsonx_lib::json;
114/// use rpc_io::{ErrorCode, ErrorObject};
115///
116/// let error = ErrorObject::new(ErrorCode(1001), "stale version")
117///     .with_data(json!({ "expected": 4 }));
118/// assert_eq!(error.code(), ErrorCode(1001));
119/// assert_eq!(error.message(), "stale version");
120/// assert_eq!(error.data().map(|d| d.as_str()), Some(r#"{"expected":4}"#));
121/// ```
122#[derive(Clone, Debug, PartialEq, Eq)]
123pub struct ErrorObject {
124    code: ErrorCode,
125    message: Cow<'static, str>,
126    data: Option<Raw<'static>>,
127}
128
129impl ErrorObject {
130    /// An error with `code` and `message` and no data.
131    ///
132    /// # Examples
133    ///
134    /// ```
135    /// let e = rpc_io::ErrorObject::new(rpc_io::ErrorCode(7), "nope");
136    /// assert_eq!(e.to_string(), "nope (code 7)");
137    /// ```
138    #[must_use]
139    pub fn new(code: ErrorCode, message: impl Into<Cow<'static, str>>) -> Self {
140        Self {
141            code,
142            message: message.into(),
143            data: None,
144        }
145    }
146
147    /// Attaches `data`, any JSON value, replacing data set before.
148    ///
149    /// # Examples
150    ///
151    /// ```
152    /// let e = rpc_io::ErrorObject::invalid_params("bad line").with_data(12);
153    /// assert_eq!(e.data().map(|d| d.as_str()), Some("12"));
154    /// ```
155    #[must_use]
156    pub fn with_data<'a>(mut self, data: impl Into<Json<'a>>) -> Self {
157        self.data = Some(data.into().into_raw());
158        self
159    }
160
161    /// `-32700` parse error with `message`.
162    ///
163    /// # Examples
164    ///
165    /// ```
166    /// use rpc_io::{ErrorCode, ErrorObject};
167    ///
168    /// assert_eq!(ErrorObject::parse_error("bad").code(), ErrorCode::PARSE_ERROR);
169    /// ```
170    #[must_use]
171    pub fn parse_error(message: impl Into<Cow<'static, str>>) -> Self {
172        Self::new(ErrorCode::PARSE_ERROR, message)
173    }
174
175    /// `-32600` invalid request with `message`.
176    ///
177    /// # Examples
178    ///
179    /// ```
180    /// use rpc_io::{ErrorCode, ErrorObject};
181    ///
182    /// assert_eq!(ErrorObject::invalid_request("bad").code(), ErrorCode::INVALID_REQUEST);
183    /// ```
184    #[must_use]
185    pub fn invalid_request(message: impl Into<Cow<'static, str>>) -> Self {
186        Self::new(ErrorCode::INVALID_REQUEST, message)
187    }
188
189    /// `-32601` method not found, naming `method`.
190    ///
191    /// # Examples
192    ///
193    /// ```
194    /// let e = rpc_io::ErrorObject::method_not_found("frob");
195    /// assert_eq!(e.message(), "method not found: `frob`");
196    /// ```
197    #[must_use]
198    pub fn method_not_found(method: &str) -> Self {
199        Self::new(
200            ErrorCode::METHOD_NOT_FOUND,
201            format!("method not found: `{}`", clip(method)),
202        )
203    }
204
205    /// `-32602` invalid params with `message`.
206    ///
207    /// # Examples
208    ///
209    /// ```
210    /// use rpc_io::{ErrorCode, ErrorObject};
211    ///
212    /// let e = ErrorObject::invalid_params("`line` must be an integer");
213    /// assert_eq!(e.code(), ErrorCode::INVALID_PARAMS);
214    /// ```
215    #[must_use]
216    pub fn invalid_params(message: impl Into<Cow<'static, str>>) -> Self {
217        Self::new(ErrorCode::INVALID_PARAMS, message)
218    }
219
220    /// `-32603` internal error with `message`.
221    ///
222    /// # Examples
223    ///
224    /// ```
225    /// use rpc_io::{ErrorCode, ErrorObject};
226    ///
227    /// assert_eq!(ErrorObject::internal_error("x").code(), ErrorCode::INTERNAL_ERROR);
228    /// ```
229    #[must_use]
230    pub fn internal_error(message: impl Into<Cow<'static, str>>) -> Self {
231        Self::new(ErrorCode::INTERNAL_ERROR, message)
232    }
233
234    /// The code.
235    ///
236    /// # Examples
237    ///
238    /// ```
239    /// assert_eq!(rpc_io::ErrorObject::new(rpc_io::ErrorCode(3), "m").code().0, 3);
240    /// ```
241    #[inline]
242    #[must_use]
243    pub const fn code(&self) -> ErrorCode {
244        self.code
245    }
246
247    /// The message.
248    ///
249    /// # Examples
250    ///
251    /// ```
252    /// assert_eq!(rpc_io::ErrorObject::internal_error("boom").message(), "boom");
253    /// ```
254    #[inline]
255    #[must_use]
256    pub fn message(&self) -> &str {
257        &self.message
258    }
259
260    /// The data, if any, as JSON text.
261    ///
262    /// # Examples
263    ///
264    /// ```
265    /// assert!(rpc_io::ErrorObject::internal_error("boom").data().is_none());
266    /// ```
267    #[inline]
268    #[must_use]
269    pub fn data(&self) -> Option<&Raw<'static>> {
270        self.data.as_ref()
271    }
272
273    /// Builds an error from fields read off the wire.
274    pub(crate) fn from_parts(code: i64, message: String, data: Option<Raw<'static>>) -> Self {
275        Self {
276            code: ErrorCode(code),
277            message: Cow::Owned(message),
278            data,
279        }
280    }
281
282    /// Appends the error object as JSON.
283    pub(crate) fn write(&self, out: &mut String) {
284        out.push_str("{\"code\":");
285        text::push_i64(out, self.code.0);
286        out.push_str(",\"message\":");
287        jsonx_lib::write_string(out, &self.message);
288        if let Some(data) = &self.data {
289            out.push_str(",\"data\":");
290            out.push_str(data.as_str());
291        }
292        out.push('}');
293    }
294}
295
296impl fmt::Display for ErrorObject {
297    /// `"<message> (code <code>)"`.
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        write!(f, "{} (code {})", self.message, self.code.0)
300    }
301}
302
303impl core::error::Error for ErrorObject {}
304
305impl From<jsonx_lib::Error> for ErrorObject {
306    /// An `-32602` invalid-params error describing why the params did not
307    /// parse, so a handler can apply `?` to `params.parse()`.
308    fn from(error: jsonx_lib::Error) -> Self {
309        Self::invalid_params(format!("invalid params: {error}"))
310    }
311}
312
313/// At most the first 128 bytes of `text` (on a character boundary), with an
314/// ellipsis when cut, so peer-controlled text quoted in a message stays short.
315pub(crate) fn clip(text: &str) -> Cow<'_, str> {
316    const MAX: usize = 128;
317    if text.len() <= MAX {
318        return Cow::Borrowed(text);
319    }
320    let mut end = MAX;
321    while !text.is_char_boundary(end) {
322        end -= 1;
323    }
324    Cow::Owned(format!("{}\u{2026}", &text[..end]))
325}
326
327#[cfg(test)]
328#[allow(clippy::panic)]
329mod tests {
330    use alloc::string::ToString;
331
332    use super::*;
333
334    #[test]
335    fn test_write_with_and_without_data() {
336        let mut out = String::new();
337        ErrorObject::new(ErrorCode(-1), "a\"b").write(&mut out);
338        assert_eq!(out, r#"{"code":-1,"message":"a\"b"}"#);
339        out.clear();
340        ErrorObject::internal_error("x")
341            .with_data(jsonx_lib::json!([1]))
342            .write(&mut out);
343        assert_eq!(out, r#"{"code":-32603,"message":"x","data":[1]}"#);
344    }
345
346    #[test]
347    fn test_clip_respects_char_boundaries() {
348        let long = "é".repeat(100);
349        let clipped = clip(&long);
350        assert!(clipped.len() <= 128 + '\u{2026}'.len_utf8());
351        assert!(clipped.ends_with('\u{2026}'));
352        assert_eq!(clip("short"), "short");
353    }
354
355    #[test]
356    fn test_from_jsonx_error_is_invalid_params() {
357        let Err(e) = jsonx_lib::parse("[") else {
358            panic!("`[` must not parse")
359        };
360        let error = ErrorObject::from(e);
361        assert_eq!(error.code(), ErrorCode::INVALID_PARAMS);
362        assert!(error.message().starts_with("invalid params: "));
363        assert_eq!(
364            error.to_string(),
365            alloc::format!("{} (code -32602)", error.message())
366        );
367    }
368}