Skip to main content

proton_sdk/
error.rs

1//! Error types for the core SDK.
2
3use crate::api::ResponseCode;
4
5pub type Result<T> = std::result::Result<T, ProtonError>;
6
7/// Top-level error for the core SDK.
8#[derive(Debug, thiserror::Error)]
9pub enum ProtonError {
10    /// The API returned a non-success response envelope or HTTP status.
11    #[error(transparent)]
12    Api(#[from] ProtonApiError),
13
14    /// Transport-level failure (DNS, TLS, timeout, connection reset).
15    #[error("HTTP transport error: {0}")]
16    Transport(#[from] reqwest::Error),
17
18    /// Failed to (de)serialize a request or response body.
19    #[error("serialization error: {0}")]
20    Serialization(#[from] serde_json::Error),
21
22    /// A cryptographic operation failed.
23    #[error("cryptography error: {0}")]
24    Crypto(#[from] crate::crypto::CryptoError),
25
26    /// The SDK was used in a way that violates an invariant.
27    #[error("invalid operation: {0}")]
28    InvalidOperation(String),
29}
30
31impl ProtonError {
32    pub fn invalid_operation(message: impl Into<String>) -> Self {
33        Self::InvalidOperation(message.into())
34    }
35}
36
37/// An error reported by the Proton API in its response envelope.
38#[derive(Debug, Clone, thiserror::Error)]
39#[error("proton api error {code:?} (http {http_status}): {message}")]
40pub struct ProtonApiError {
41    /// Application-level response code from the `Code` field.
42    pub code: ResponseCode,
43    /// HTTP status code of the response.
44    pub http_status: u16,
45    /// Human-readable message from the `Error` field, if present.
46    pub message: String,
47}
48
49impl ProtonApiError {
50    pub fn is_unauthorized(&self) -> bool {
51        self.http_status == 401
52    }
53
54    pub fn is_invalid_refresh_token(&self) -> bool {
55        matches!(self.code, ResponseCode::InvalidRefreshToken)
56    }
57
58    /// The token lacks a scope the endpoint requires — no amount of refreshing
59    /// fixes it; the user must authenticate with their password again.
60    pub fn is_insufficient_scope(&self) -> bool {
61        matches!(self.code, ResponseCode::InsufficientScope)
62    }
63}