bitwarden_core/
error.rs

1//! Errors that can occur when using this SDK
2
3use std::fmt::Debug;
4
5use bitwarden_api_api::apis::Error as ApiApisError;
6use bitwarden_api_identity::apis::Error as IdentityError;
7use reqwest::StatusCode;
8use thiserror::Error;
9
10macro_rules! impl_bitwarden_error {
11    ($name:ident, $error:ident) => {
12        impl<T> From<$name<T>> for $error {
13            fn from(e: $name<T>) -> Self {
14                match e {
15                    $name::Reqwest(e) => Self::Reqwest(e),
16                    $name::ResponseError(e) => Self::ResponseContent {
17                        status: e.status,
18                        message: e.content,
19                    },
20                    $name::Serde(e) => Self::Serde(e),
21                    $name::Io(e) => Self::Io(e),
22                }
23            }
24        }
25    };
26}
27
28/// Errors from performing network requests.
29#[allow(missing_docs)]
30#[derive(Debug, Error)]
31pub enum ApiError {
32    #[error(transparent)]
33    Reqwest(#[from] reqwest::Error),
34    #[error(transparent)]
35    Serde(#[from] serde_json::Error),
36    #[error(transparent)]
37    Io(#[from] std::io::Error),
38
39    #[error("Received error message from server: [{}] {}", .status, .message)]
40    ResponseContent { status: StatusCode, message: String },
41}
42
43impl_bitwarden_error!(ApiApisError, ApiError);
44impl_bitwarden_error!(IdentityError, ApiError);
45
46/// Client is not authenticated or the session has expired.
47#[derive(Debug, Error)]
48#[error("The client is not authenticated or the session has expired")]
49pub struct NotAuthenticatedError;
50
51/// Missing required field.
52#[derive(Debug, Error)]
53#[error("The response received was missing a required field: {0}")]
54pub struct MissingFieldError(pub &'static str);
55
56/// Client vault is locked.
57#[derive(Debug, Error)]
58#[error("The client vault is locked and needs to be unlocked before use")]
59pub struct VaultLockedError;
60
61/// Wrong password.
62#[derive(Debug, thiserror::Error)]
63#[error("Wrong password")]
64pub struct WrongPasswordError;
65
66/// Missing private key.
67#[derive(Debug, thiserror::Error)]
68#[error("Missing private key")]
69pub struct MissingPrivateKeyError;
70
71/// This macro is used to require that a value is present or return an error otherwise.
72/// It is equivalent to using `val.ok_or(Error::MissingFields)?`, but easier to use and
73/// with a more descriptive error message.
74/// Note that this macro will return early from the function if the value is not present.
75#[macro_export]
76macro_rules! require {
77    ($val:expr) => {
78        match $val {
79            Some(val) => val,
80            None => return Err($crate::MissingFieldError(stringify!($val)).into()),
81        }
82    };
83}