1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use crate::resource::{ErrorResponse, OAuth2ErrorResponse};
use reqwest::StatusCode;
use thiserror::Error;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Error)]
#[error(transparent)]
pub struct Error {
inner: Box<ErrorKind>,
}
#[derive(Debug, Error)]
enum ErrorKind {
#[error("Request error: {0}")]
RequestError(reqwest::Error),
#[error("Unexpected response: {reason}")]
UnexpectedResponse { reason: &'static str },
#[error("Api error with {status}: ({}) {}", .response.code, .response.message)]
ErrorResponse {
status: StatusCode,
response: ErrorResponse,
},
#[error("OAuth2 error with {status}: ({}) {}", .response.error, .response.error_description)]
OAuth2Error {
status: StatusCode,
response: OAuth2ErrorResponse,
},
}
impl Error {
pub(crate) fn from_error_response(status: StatusCode, response: ErrorResponse) -> Self {
Self {
inner: Box::new(ErrorKind::ErrorResponse { status, response }),
}
}
pub(crate) fn unexpected_response(reason: &'static str) -> Self {
Self {
inner: Box::new(ErrorKind::UnexpectedResponse { reason }),
}
}
pub(crate) fn from_oauth2_error_response(
status: StatusCode,
response: OAuth2ErrorResponse,
) -> Self {
Self {
inner: Box::new(ErrorKind::OAuth2Error { status, response }),
}
}
pub fn error_response(&self) -> Option<&ErrorResponse> {
match &*self.inner {
ErrorKind::ErrorResponse { response, .. } => Some(response),
_ => None,
}
}
pub fn oauth2_error_response(&self) -> Option<&OAuth2ErrorResponse> {
match &*self.inner {
ErrorKind::OAuth2Error { response, .. } => Some(response),
_ => None,
}
}
pub fn status_code(&self) -> Option<StatusCode> {
match &*self.inner {
ErrorKind::RequestError(source) => source.status(),
ErrorKind::UnexpectedResponse { .. } => None,
ErrorKind::ErrorResponse { status, .. } | ErrorKind::OAuth2Error { status, .. } => {
Some(*status)
}
}
}
}
impl From<reqwest::Error> for Error {
fn from(source: reqwest::Error) -> Self {
Self {
inner: Box::new(ErrorKind::RequestError(source)),
}
}
}