lsp_lang/error.rs
1//! [`Error`]: what ends a session, or fails a write to the client.
2
3use std::{fmt, io};
4
5use jsonx_lib::Kind;
6use rpc_io::FrameError;
7
8/// Something went wrong in the server itself, as opposed to a request that
9/// failed, which is a [`ResponseError`](crate::ResponseError) sent to the
10/// client.
11///
12/// [`Server::run`](crate::Server::run) returns one when the session cannot go
13/// on: the connection failed or closed, the client's framing broke, or the
14/// client exited without the shutdown handshake. In each case the editor is
15/// gone or the stream is unusable, so the right response is to exit the
16/// process with a non-zero status, as the protocol asks. [`Error::Closed`] and
17/// [`Error::InvalidParams`] are the exceptions: they come from a handler's
18/// own sends ([`Context::notify`](crate::Context::notify),
19/// [`Context::request`](crate::Context::request)) and describe that one send.
20///
21/// Malformed JSON *inside* a well-framed message is not an `Error`: the server
22/// answers it with a protocol error and carries on, as it does for a message
23/// over the size limit.
24///
25/// # Examples
26///
27/// ```
28/// use lsp_lang::Error;
29///
30/// fn exit_code(result: Result<(), Error>) -> i32 {
31/// match result {
32/// Ok(()) => 0, // `shutdown` then `exit`: a clean stop.
33/// Err(Error::ExitWithoutShutdown) => 1,
34/// Err(_) => 1,
35/// }
36/// }
37/// assert_eq!(exit_code(Err(Error::Disconnected)), 1);
38/// ```
39#[derive(Debug)]
40#[non_exhaustive]
41pub enum Error {
42 /// Reading from or writing to the client failed.
43 ///
44 /// The connection is broken; exit. The wrapped error is the transport's.
45 Io(io::Error),
46
47 /// The client's input ended before it sent `exit`, typically because the
48 /// editor closed or crashed, or ended partway through a message.
49 Disconnected,
50
51 /// The input lost its base-protocol framing, so the stream cannot be split
52 /// into messages any more: no `Content-Length`, a malformed length, an
53 /// over-long or malformed header. A message that is merely over the size
54 /// limit is not this error; it is skipped and refused, and the session
55 /// goes on (see
56 /// [`Server::with_message_limit`](crate::Server::with_message_limit)).
57 Frame(FrameError),
58
59 /// The client sent `exit` without a `shutdown` request first. The protocol
60 /// asks the server to exit with status `1` in this case.
61 ExitWithoutShutdown,
62
63 /// The connection is closed, so nothing more can be sent: the session has
64 /// ended, or writing to the client failed earlier.
65 Closed,
66
67 /// A notification's or request's `params` was not an array, an object, or
68 /// `null`. Nothing was sent. Inside a request handler, `?` turns it into an
69 /// [`INTERNAL_ERROR`](crate::ResponseError::INTERNAL_ERROR) response.
70 InvalidParams(Kind),
71}
72
73impl fmt::Display for Error {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 match self {
76 Error::Io(e) => write!(f, "language server I/O failed: {e}"),
77 Error::Disconnected => f.write_str("the client closed the connection before `exit`"),
78 Error::Frame(e) => write!(f, "invalid message framing: {e}"),
79 Error::ExitWithoutShutdown => {
80 f.write_str("the client sent `exit` without requesting `shutdown` first")
81 }
82 Error::Closed => f.write_str("the connection is closed"),
83 Error::InvalidParams(kind) => {
84 write!(f, "params must be an array, an object, or null, not {kind}")
85 }
86 }
87 }
88}
89
90impl std::error::Error for Error {
91 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
92 match self {
93 Error::Io(e) => Some(e),
94 Error::Frame(e) => Some(e),
95 _ => None,
96 }
97 }
98}
99
100impl From<io::Error> for Error {
101 fn from(error: io::Error) -> Self {
102 Error::Io(error)
103 }
104}
105
106impl From<rpc_io::Error> for Error {
107 /// Maps the transport's error: framing and I/O failures keep their
108 /// meaning, bad outgoing params stay bad params, and anything else about a
109 /// closed or already-answered connection is [`Error::Closed`].
110 fn from(error: rpc_io::Error) -> Self {
111 match error {
112 rpc_io::Error::Io(e) => Error::Io(e),
113 rpc_io::Error::Frame(e) => Error::Frame(e),
114 rpc_io::Error::InvalidParams(kind) => Error::InvalidParams(kind),
115 _ => Error::Closed,
116 }
117 }
118}
119
120#[cfg(test)]
121mod tests {
122 use std::error::Error as _;
123
124 use super::*;
125
126 #[test]
127 fn test_error_display_names_the_problem() {
128 let cases = [
129 Error::Io(io::Error::other("pipe")),
130 Error::Disconnected,
131 Error::Frame(FrameError::MissingContentLength),
132 Error::ExitWithoutShutdown,
133 Error::Closed,
134 Error::InvalidParams(Kind::Number),
135 ];
136 for e in cases {
137 assert!(!e.to_string().is_empty());
138 }
139 assert!(
140 Error::InvalidParams(Kind::Number)
141 .to_string()
142 .contains("number")
143 );
144 }
145
146 #[test]
147 fn test_error_source_exposes_wrapped_errors() {
148 assert!(Error::Io(io::Error::other("pipe")).source().is_some());
149 assert!(Error::Frame(FrameError::InvalidHeader).source().is_some());
150 assert!(Error::Disconnected.source().is_none());
151 }
152
153 #[test]
154 fn test_error_from_transport_error() {
155 assert!(matches!(Error::from(rpc_io::Error::Closed), Error::Closed));
156 assert!(matches!(
157 Error::from(rpc_io::Error::AlreadyAnswered),
158 Error::Closed
159 ));
160 assert!(matches!(
161 Error::from(rpc_io::Error::InvalidParams(Kind::Bool)),
162 Error::InvalidParams(Kind::Bool)
163 ));
164 assert!(matches!(
165 Error::from(rpc_io::Error::Frame(FrameError::Truncated)),
166 Error::Frame(FrameError::Truncated)
167 ));
168 }
169}