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/// Client's user ID is already set.
52#[derive(Debug, Error)]
53#[error("The client user ID is already set")]
54pub struct UserIdAlreadySetError;
55
56/// Missing required field.
57#[derive(Debug, Error)]
58#[error("The response received was missing a required field: {0}")]
59pub struct MissingFieldError(pub &'static str);
60
61/// Client vault is locked.
62#[derive(Debug, Error)]
63#[error("The client vault is locked and needs to be unlocked before use")]
64pub struct VaultLockedError;
65
66/// Wrong password.
67#[derive(Debug, thiserror::Error)]
68#[error("Wrong password")]
69pub struct WrongPasswordError;
70
71/// Missing private key.
72#[derive(Debug, thiserror::Error)]
73#[error("Missing private key")]
74pub struct MissingPrivateKeyError;
75
76/// This macro is used to require that a value is present or return an error otherwise.
77/// It is equivalent to using `val.ok_or(Error::MissingFields)?`, but easier to use and
78/// with a more descriptive error message.
79/// Note that this macro will return early from the function if the value is not present.
80#[macro_export]
81macro_rules! require {
82    ($val:expr) => {
83        match $val {
84            Some(val) => val,
85            None => return Err($crate::MissingFieldError(stringify!($val)).into()),
86        }
87    };
88}