Skip to main content

iterm2_client/
error.rs

1//! Error types for iTerm2 client operations.
2
3use std::io;
4
5const MAX_SERVER_ERROR_LEN: usize = 512;
6
7/// Errors that can occur when communicating with iTerm2.
8#[derive(Debug, thiserror::Error)]
9pub enum Error {
10    /// WebSocket protocol error.
11    #[error("WebSocket error: {0}")]
12    WebSocket(#[from] tokio_tungstenite::tungstenite::Error),
13
14    /// I/O error (socket, file system, etc.).
15    #[error("I/O error: {0}")]
16    Io(#[from] io::Error),
17
18    /// Failed to decode a protobuf message from the server.
19    #[error("Protobuf decode error: {0}")]
20    Decode(#[from] prost::DecodeError),
21
22    /// The server returned an error string in the response.
23    #[error("API error from server: {0}")]
24    Api(String),
25
26    /// An API operation returned a non-OK status code.
27    #[error("Non-OK status: {0}")]
28    Status(String),
29
30    /// Authentication failed (bad credentials, osascript failure, etc.).
31    #[error("Authentication failed: {0}")]
32    Auth(String),
33
34    /// The WebSocket connection was closed unexpectedly.
35    #[error("Connection closed")]
36    ConnectionClosed,
37
38    /// A request did not receive a response within the timeout period.
39    #[error("Request timed out after {0:?}")]
40    Timeout(std::time::Duration),
41
42    /// The server returned a response type that doesn't match the request.
43    #[error("Unexpected response: expected {expected}, got different submessage")]
44    UnexpectedResponse {
45        /// The response type that was expected.
46        expected: &'static str,
47    },
48}
49
50/// Create an [`Error::Api`], truncating the server message to prevent
51/// unbounded or malicious strings from propagating through error chains.
52pub(crate) fn api_error(server_msg: &str) -> Error {
53    if server_msg.len() <= MAX_SERVER_ERROR_LEN {
54        Error::Api(server_msg.to_string())
55    } else {
56        let truncated: String = server_msg.chars().take(MAX_SERVER_ERROR_LEN).collect();
57        Error::Api(format!("{}... [truncated]", truncated))
58    }
59}
60
61/// A specialized `Result` type for iTerm2 client operations.
62pub type Result<T> = std::result::Result<T, Error>;