Skip to main content

elasticctl_core/
error.rs

1//! Classify errors returned to the user.
2
3use serde_json::{Value, json};
4
5/// A stable error classification.
6///
7/// Its string values are part of the CLI's public API. Changing one requires a
8/// minor version bump.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum ErrorKind {
11    Auth,
12    Permission,
13    NotFound,
14    Conflict,
15    Unsupported,
16    Http,
17    Connection,
18    Timeout,
19    Error,
20}
21
22impl ErrorKind {
23    pub fn as_str(&self) -> &'static str {
24        match self {
25            Self::Auth => "auth",
26            Self::Permission => "permission",
27            Self::NotFound => "not_found",
28            Self::Conflict => "conflict",
29            Self::Unsupported => "unsupported",
30            Self::Http => "http",
31            Self::Connection => "connection",
32            Self::Timeout => "timeout",
33            Self::Error => "error",
34        }
35    }
36
37    pub fn from_status(status: u16) -> Self {
38        match status {
39            401 => Self::Auth,
40            403 => Self::Permission,
41            404 => Self::NotFound,
42            409 => Self::Conflict,
43            _ => Self::Http,
44        }
45    }
46}
47
48#[derive(Debug, Clone, thiserror::Error)]
49#[error("{message}")]
50pub struct Error {
51    pub kind: ErrorKind,
52    pub http_status: Option<u16>,
53    pub message: String,
54}
55
56impl Error {
57    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
58        Self {
59            kind,
60            http_status: None,
61            message: message.into(),
62        }
63    }
64
65    pub fn with_status(kind: ErrorKind, status: u16, message: impl Into<String>) -> Self {
66        Self {
67            kind,
68            http_status: Some(status),
69            message: message.into(),
70        }
71    }
72
73    /// Classify an HTTP error response.
74    ///
75    /// Kibana returns `{"statusCode":..,"error":..,"message":..}`. The Elastic
76    /// Cloud edge proxy returns `{"ok":false,"message":".."}`. The latter also
77    /// appears when a project rename leaves a hostname unresolved.
78    pub fn from_response_body(status: u16, body: &str) -> Self {
79        let kind = ErrorKind::from_status(status);
80        let message = serde_json::from_str::<Value>(body)
81            .ok()
82            .and_then(|v| v.get("message")?.as_str().map(str::to_owned))
83            .unwrap_or_else(|| {
84                let trimmed = body.trim();
85                if trimmed.is_empty() {
86                    format!("HTTP {status}")
87                } else {
88                    format!("HTTP {status}: {trimmed}")
89                }
90            });
91        Self {
92            kind,
93            http_status: Some(status),
94            message,
95        }
96    }
97
98    /// Return the JSON object written to stderr when a command fails.
99    pub fn to_envelope(&self) -> Value {
100        let mut inner = json!({ "kind": self.kind.as_str(), "message": self.message });
101        if let Some(status) = self.http_status {
102            inner["http_status"] = json!(status);
103        }
104        json!({ "error": inner })
105    }
106}
107
108pub type Result<T> = std::result::Result<T, Error>;
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn kind_maps_from_http_status() {
116        assert_eq!(ErrorKind::from_status(401), ErrorKind::Auth);
117        assert_eq!(ErrorKind::from_status(403), ErrorKind::Permission);
118        assert_eq!(ErrorKind::from_status(404), ErrorKind::NotFound);
119        assert_eq!(ErrorKind::from_status(409), ErrorKind::Conflict);
120        assert_eq!(ErrorKind::from_status(500), ErrorKind::Http);
121        assert_eq!(ErrorKind::from_status(418), ErrorKind::Http);
122    }
123
124    #[test]
125    fn kind_str_values_are_the_documented_taxonomy() {
126        assert_eq!(ErrorKind::Auth.as_str(), "auth");
127        assert_eq!(ErrorKind::Permission.as_str(), "permission");
128        assert_eq!(ErrorKind::NotFound.as_str(), "not_found");
129        assert_eq!(ErrorKind::Conflict.as_str(), "conflict");
130        assert_eq!(ErrorKind::Unsupported.as_str(), "unsupported");
131        assert_eq!(ErrorKind::Http.as_str(), "http");
132        assert_eq!(ErrorKind::Connection.as_str(), "connection");
133        assert_eq!(ErrorKind::Timeout.as_str(), "timeout");
134        assert_eq!(ErrorKind::Error.as_str(), "error");
135    }
136
137    // Kibana error envelope.
138    #[test]
139    fn parses_the_kibana_error_envelope() {
140        let body = r#"{"statusCode":400,"error":"Bad Request","message":"rule_id already exists"}"#;
141        let err = Error::from_response_body(400, body);
142        assert_eq!(err.kind, ErrorKind::Http);
143        assert_eq!(err.http_status, Some(400));
144        assert_eq!(err.message, "rule_id already exists");
145    }
146
147    // Elastic Cloud edge-proxy error envelope.
148    #[test]
149    fn parses_the_cloud_edge_proxy_envelope() {
150        let body = r#"{"ok":false,"message":"Unknown resource."}"#;
151        let err = Error::from_response_body(404, body);
152        assert_eq!(err.kind, ErrorKind::NotFound);
153        assert_eq!(err.message, "Unknown resource.");
154    }
155
156    #[test]
157    fn falls_back_to_the_raw_body_when_it_is_not_json() {
158        let err = Error::from_response_body(502, "<html>bad gateway</html>");
159        assert_eq!(err.kind, ErrorKind::Http);
160        assert_eq!(err.http_status, Some(502));
161        assert!(err.message.contains("bad gateway"));
162    }
163
164    #[test]
165    fn falls_back_when_json_has_no_message_field() {
166        let err = Error::from_response_body(500, r#"{"unexpected":true}"#);
167        assert_eq!(err.kind, ErrorKind::Http);
168        assert!(!err.message.is_empty());
169    }
170
171    #[test]
172    fn envelope_is_the_documented_shape() {
173        let err = Error::with_status(ErrorKind::Permission, 403, "nope");
174        let env = err.to_envelope();
175        assert_eq!(env["error"]["kind"], "permission");
176        assert_eq!(env["error"]["http_status"], 403);
177        assert_eq!(env["error"]["message"], "nope");
178    }
179
180    #[test]
181    fn envelope_omits_http_status_when_absent() {
182        let err = Error::new(ErrorKind::Connection, "dns failure");
183        let env = err.to_envelope();
184        assert_eq!(env["error"]["kind"], "connection");
185        assert!(env["error"].get("http_status").is_none());
186    }
187}