Skip to main content

bitwarden_api_base/
error.rs

1//! Error types for API operations.
2
3use std::{convert::Infallible, error, fmt, marker::PhantomData};
4
5use serde::{Deserialize, Serialize};
6
7/// Response content from a failed API call.
8#[derive(Debug, Serialize, Deserialize)]
9#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
10pub struct ResponseContent {
11    /// HTTP status code of the response.
12    #[serde(with = "crate::status_code_serializer")]
13    pub status: reqwest::StatusCode,
14    /// Response body content.
15    pub message: String,
16}
17
18/// Errors that can occur during API operations.
19///
20/// This type is intentionally not exposed over UniFFI. It is always wrapped into
21/// `bitwarden_core::ApiError` before crossing the FFI boundary, and that type carries the
22/// `uniffi::Error` derive. Deriving `uniffi::Error` here as well would export a second error type
23/// named `Error`, which collides with the `Swift.Error` protocol in the generated Swift bindings.
24#[derive(Debug)]
25pub enum Error<T = ()> {
26    /// Error from the reqwest HTTP client.
27    Reqwest(reqwest::Error),
28    /// Error from the reqwest middleware.
29    ReqwestMiddleware(reqwest_middleware::Error),
30    /// JSON serialization/deserialization error.
31    Serde(serde_json::Error),
32    /// I/O error.
33    Io(std::io::Error),
34    /// API returned an error response.
35    Response(ResponseContent),
36
37    /// Phantom variant to keep the unused `T` parameter alive without affecting downstream
38    /// `impl<T> From<Error<T>> for FooError` impls. Uninhabited via [`Infallible`].
39    #[doc(hidden)]
40    _Phantom(PhantomData<T>, Infallible),
41}
42
43impl<T> fmt::Display for Error<T> {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        let (module, e) = match self {
46            Error::Reqwest(e) => ("reqwest", e.to_string()),
47            Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()),
48            Error::Serde(e) => ("serde", e.to_string()),
49            Error::Io(e) => ("IO", e.to_string()),
50            Error::Response(e) => ("response", format!("status code {}", e.status)),
51            Error::_Phantom(_, _) => unreachable!(),
52        };
53        write!(f, "error in {}: {}", module, e)
54    }
55}
56
57impl<T: fmt::Debug> error::Error for Error<T> {
58    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
59        Some(match self {
60            Error::Reqwest(e) => e,
61            Error::ReqwestMiddleware(e) => e,
62            Error::Serde(e) => e,
63            Error::Io(e) => e,
64            Error::Response(_) | Error::_Phantom(_, _) => return None,
65        })
66    }
67}
68
69impl<T> From<reqwest::Error> for Error<T> {
70    fn from(e: reqwest::Error) -> Self {
71        Error::Reqwest(e)
72    }
73}
74
75impl<T> From<reqwest_middleware::Error> for Error<T> {
76    fn from(e: reqwest_middleware::Error) -> Self {
77        Error::ReqwestMiddleware(e)
78    }
79}
80
81impl<T> From<serde_json::Error> for Error<T> {
82    fn from(e: serde_json::Error) -> Self {
83        Error::Serde(e)
84    }
85}
86
87impl<T> From<std::io::Error> for Error<T> {
88    fn from(e: std::io::Error) -> Self {
89        Error::Io(e)
90    }
91}
92
93impl<T> From<ResponseContent> for Error<T> {
94    fn from(value: ResponseContent) -> Self {
95        Self::Response(value)
96    }
97}