Skip to main content

rusted_mail/
error.rs

1//! Error types exposed by the engine.
2//!
3//! Native implementations retain detailed [`Error`] variants while
4//! external callers receive a serializable [`MailError`] with a stable
5//! [`ErrorCode`]. This keeps protocol-specific implementation details out of
6//! the cross-language error contract.
7
8use crate::internal_imap as imap_rs;
9use imap_rs::client::ClientError;
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13/// Stable, machine-readable category for a mail operation failure.
14///
15/// Variant names serialize as `SCREAMING_SNAKE_CASE`, making the values safe
16/// to match in Kotlin, Java, or another API consumer without parsing the human
17/// readable message.
18#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
19#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
20#[non_exhaustive]
21pub enum ErrorCode {
22    /// A connection, transport, DNS, or timeout failure.
23    Network,
24    /// A TLS negotiation or certificate-validation failure.
25    Tls,
26    /// Credentials were rejected or authentication otherwise failed.
27    Auth,
28    /// The requested authentication mechanism is unavailable.
29    UnsupportedAuth,
30    /// Encryption, signing, verification, or key processing failed.
31    Crypto,
32    /// The request was malformed or violated an API precondition.
33    InvalidRequest,
34    /// The requested session or resource does not exist.
35    NotFound,
36    /// The caller cancelled the operation.
37    Cancelled,
38    /// The remote mail server rejected or could not complete the operation.
39    Server,
40    /// An unexpected local failure occurred.
41    Internal,
42}
43
44/// Serializable error returned across the native integration boundary.
45///
46/// The structure serializes with `camelCase` field names. Consumers should
47/// branch on [`code`](Self::code) and treat [`message`](Self::message) as a
48/// diagnostic intended for logs or user-facing error detail.
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50#[serde(rename_all = "camelCase")]
51pub struct MailError {
52    /// Stable category suitable for programmatic error handling.
53    pub code: ErrorCode,
54    /// Human-readable description of the failure.
55    pub message: String,
56}
57
58/// Error returned by Rusted Mail operations.
59///
60/// Convert this type with [`public`](Self::public) before serializing it for an
61/// external caller. Its [`std::fmt::Display`] implementation includes a short
62/// category prefix and the underlying diagnostic where applicable.
63#[derive(Debug, Error)]
64#[non_exhaustive]
65pub enum Error {
66    /// The caller supplied an invalid request.
67    #[error("invalid request: {0}")]
68    InvalidRequest(String),
69    /// A requested session or resource was not found.
70    #[error("session not found")]
71    NotFound,
72    /// The operation was cancelled before completion.
73    #[error("operation cancelled")]
74    Cancelled,
75    /// The server or build does not support the requested authentication path.
76    #[error("authentication is not supported by this server or crate path: {0}")]
77    UnsupportedAuth(String),
78    /// Authentication failed.
79    #[error("authentication failed: {0}")]
80    Auth(String),
81    /// A cryptographic operation failed.
82    #[error("crypto error: {0}")]
83    Crypto(String),
84    /// A network or transport operation failed.
85    #[error("network error: {0}")]
86    Network(String),
87    /// A remote server rejected or failed an operation.
88    #[error("server error: {0}")]
89    Server(String),
90    /// An unexpected local failure occurred.
91    #[error("internal error: {0}")]
92    Internal(String),
93}
94
95impl Error {
96    /// Returns the stable category corresponding to this detailed error.
97    #[must_use]
98    pub fn code(&self) -> ErrorCode {
99        match self {
100            Self::InvalidRequest(_) => ErrorCode::InvalidRequest,
101            Self::NotFound => ErrorCode::NotFound,
102            Self::Cancelled => ErrorCode::Cancelled,
103            Self::UnsupportedAuth(_) => ErrorCode::UnsupportedAuth,
104            Self::Auth(_) => ErrorCode::Auth,
105            Self::Crypto(_) => ErrorCode::Crypto,
106            Self::Network(_) => ErrorCode::Network,
107            Self::Server(_) => ErrorCode::Server,
108            Self::Internal(_) => ErrorCode::Internal,
109        }
110    }
111
112    /// Converts the detailed error into its serializable public representation.
113    ///
114    /// The returned message is the error's [`std::fmt::Display`] output.
115    #[must_use]
116    pub fn public(self) -> MailError {
117        MailError {
118            code: self.code(),
119            message: self.to_string(),
120        }
121    }
122}
123
124/// Legacy name used by the JNI compatibility layer.
125///
126/// New Rust integrations should use [`Error`].
127#[doc(hidden)]
128pub type MailJniError = Error;
129
130#[doc(hidden)]
131#[must_use]
132#[allow(clippy::needless_pass_by_value)] // Used directly as a Result::map_err callback.
133pub fn map_imap_error(error: ClientError) -> MailJniError {
134    if is_reconnectable_imap_error(&error) {
135        return MailJniError::Network(error.to_string());
136    }
137
138    if matches!(error, ClientError::UnsupportedCapability(_)) {
139        return MailJniError::UnsupportedAuth(error.to_string());
140    }
141
142    let message = error.to_string();
143    if message.to_ascii_lowercase().contains("auth")
144        || message.to_ascii_lowercase().contains("login")
145    {
146        MailJniError::Auth(message)
147    } else if message.to_ascii_lowercase().contains("unsupported") {
148        MailJniError::UnsupportedAuth(message)
149    } else if message.to_ascii_lowercase().contains("timeout") {
150        MailJniError::Network(message)
151    } else {
152        MailJniError::Server(message)
153    }
154}
155
156#[doc(hidden)]
157#[must_use]
158pub fn is_reconnectable_imap_error(error: &ClientError) -> bool {
159    matches!(
160        error,
161        ClientError::Timeout | ClientError::ConnectionClosed | ClientError::Io(_)
162    )
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn public_error_maps_each_variant_to_stable_code_and_message() {
171        let cases = vec![
172            (
173                MailJniError::InvalidRequest("bad".to_string()),
174                ErrorCode::InvalidRequest,
175            ),
176            (MailJniError::NotFound, ErrorCode::NotFound),
177            (MailJniError::Cancelled, ErrorCode::Cancelled),
178            (
179                MailJniError::UnsupportedAuth("xoauth2".to_string()),
180                ErrorCode::UnsupportedAuth,
181            ),
182            (MailJniError::Auth("denied".to_string()), ErrorCode::Auth),
183            (
184                MailJniError::Crypto("bad signature".to_string()),
185                ErrorCode::Crypto,
186            ),
187            (
188                MailJniError::Network("offline".to_string()),
189                ErrorCode::Network,
190            ),
191            (MailJniError::Server("boom".to_string()), ErrorCode::Server),
192            (
193                MailJniError::Internal("broken".to_string()),
194                ErrorCode::Internal,
195            ),
196        ];
197
198        for (error, code) in cases {
199            let message = error.to_string();
200            let public = error.public();
201            assert_eq!(public.code, code);
202            assert_eq!(public.message, message);
203        }
204    }
205
206    #[test]
207    fn imap_error_mapping_covers_auth_network_and_server_fallbacks() {
208        assert!(matches!(
209            map_imap_error(ClientError::CommandFailed(
210                "AUTHENTICATE failed".to_string()
211            )),
212            MailJniError::Auth(_)
213        ));
214        assert!(matches!(
215            map_imap_error(ClientError::Timeout),
216            MailJniError::Network(_)
217        ));
218        assert!(matches!(
219            map_imap_error(ClientError::UnsupportedCapability("IDLE")),
220            MailJniError::UnsupportedAuth(_)
221        ));
222        assert!(matches!(
223            map_imap_error(ClientError::CommandFailed("NO mailbox missing".to_string())),
224            MailJniError::Server(_)
225        ));
226    }
227}