bitwarden_api_base/
error.rs

1//! Error types for API operations.
2
3use std::{error, fmt};
4
5/// Response content from a failed API call.
6#[derive(Debug)]
7pub struct ResponseContent<T> {
8    /// HTTP status code of the response.
9    pub status: reqwest::StatusCode,
10    /// Raw response body content.
11    pub content: String,
12    /// Deserialized entity from the response.
13    pub entity: Option<T>,
14}
15
16/// Errors that can occur during API operations.
17#[derive(Debug)]
18pub enum Error<T> {
19    /// Error from the reqwest HTTP client.
20    Reqwest(reqwest::Error),
21    /// Error from the reqwest middleware.
22    ReqwestMiddleware(reqwest_middleware::Error),
23    /// JSON serialization/deserialization error.
24    Serde(serde_json::Error),
25    /// I/O error.
26    Io(std::io::Error),
27    /// API returned an error response.
28    ResponseError(ResponseContent<T>),
29}
30
31impl<T> fmt::Display for Error<T> {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        let (module, e) = match self {
34            Error::Reqwest(e) => ("reqwest", e.to_string()),
35            Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()),
36            Error::Serde(e) => ("serde", e.to_string()),
37            Error::Io(e) => ("IO", e.to_string()),
38            Error::ResponseError(e) => ("response", format!("status code {}", e.status)),
39        };
40        write!(f, "error in {}: {}", module, e)
41    }
42}
43
44impl<T: fmt::Debug> error::Error for Error<T> {
45    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
46        Some(match self {
47            Error::Reqwest(e) => e,
48            Error::ReqwestMiddleware(e) => e,
49            Error::Serde(e) => e,
50            Error::Io(e) => e,
51            Error::ResponseError(_) => return None,
52        })
53    }
54}
55
56impl<T> From<reqwest::Error> for Error<T> {
57    fn from(e: reqwest::Error) -> Self {
58        Error::Reqwest(e)
59    }
60}
61
62impl<T> From<reqwest_middleware::Error> for Error<T> {
63    fn from(e: reqwest_middleware::Error) -> Self {
64        Error::ReqwestMiddleware(e)
65    }
66}
67
68impl<T> From<serde_json::Error> for Error<T> {
69    fn from(e: serde_json::Error) -> Self {
70        Error::Serde(e)
71    }
72}
73
74impl<T> From<std::io::Error> for Error<T> {
75    fn from(e: std::io::Error) -> Self {
76        Error::Io(e)
77    }
78}