Skip to main content

rabbitmqadmin_sdk/
error.rs

1//! Error type for the RabbitMQ Management API client.
2
3use thiserror::Error;
4
5/// Errors returned by the RabbitMQ Management API client.
6#[derive(Debug, Error)]
7pub enum Error {
8    /// HTTP-level failure (DNS, connection, TLS, timeout, ...).
9    #[error("HTTP transport error: {0}")]
10    Transport(#[from] reqwest::Error),
11
12    /// The server returned a non-2xx status other than 404.
13    #[error("RabbitMQ API error {status}: {reason}")]
14    Api {
15        /// HTTP status code returned by the server.
16        status: u16,
17        /// Response body / reason returned by the server.
18        reason: String,
19    },
20
21    /// The server returned 404 for the requested resource.
22    #[error("resource not found: {0}")]
23    NotFound(String),
24
25    /// The response body could not be deserialized into the expected type.
26    ///
27    /// The raw `body` is kept for debugging; note it is unbounded in size
28    /// for v1 — a future version may truncate it.
29    #[error("failed to deserialize response body: {source}")]
30    Deserialize {
31        /// The underlying serde error.
32        source: serde_json::Error,
33        /// The raw response body that failed to deserialize.
34        body: String,
35    },
36
37    /// The base URL or a constructed request URL was invalid.
38    #[error("invalid URL: {0}")]
39    InvalidUrl(String),
40}
41
42/// Result alias using this crate's [`Error`](enum@Error) type.
43pub type Result<T> = std::result::Result<T, Error>;
44
45#[cfg(test)]
46mod tests {
47    use super::Error;
48
49    #[test]
50    fn api_error_displays_status_and_reason() {
51        let e = Error::Api {
52            status: 401,
53            reason: "not authorised".into(),
54        };
55        assert_eq!(e.to_string(), "RabbitMQ API error 401: not authorised");
56    }
57
58    #[test]
59    fn not_found_displays_identifier() {
60        let e = Error::NotFound("queue 'q1'".into());
61        assert_eq!(e.to_string(), "resource not found: queue 'q1'");
62    }
63
64    #[test]
65    fn invalid_url_displays_url() {
66        let e = Error::InvalidUrl("ht!tp://nope".into());
67        assert_eq!(e.to_string(), "invalid URL: ht!tp://nope");
68    }
69
70    #[test]
71    fn deserialize_displays_source_not_body() {
72        let source = serde_json::from_str::<String>("42").unwrap_err();
73        let e = Error::Deserialize {
74            source,
75            body: "42".into(),
76        };
77        let msg = e.to_string();
78        assert!(
79            msg.starts_with("failed to deserialize response body: "),
80            "got: {msg}"
81        );
82    }
83}