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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use std::{
error::Error as StdError,
fmt::{Display, Formatter, Result as FmtResult},
};
use reqwest::{header::InvalidHeaderValue, Error as ReqwestError, Response, StatusCode, Url};
use serde::de::{Deserialize, Deserializer, Error as DeError};
use url::ParseError as UrlError;
use crate::http::utils::deserialize_errors;
use crate::internal::prelude::{JsonMap, StdResult};
#[derive(Clone, Serialize, PartialEq, Debug)]
#[non_exhaustive]
pub struct DiscordJsonError {
pub code: isize,
pub message: String,
pub errors: Vec<DiscordJsonSingleError>,
}
impl<'de> Deserialize<'de> for DiscordJsonError {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
let mut map = JsonMap::deserialize(deserializer)?;
let code = map
.remove("code")
.ok_or_else(|| DeError::custom("expected code"))
.and_then(isize::deserialize)
.map_err(DeError::custom)?;
let message = map
.remove("message")
.ok_or_else(|| DeError::custom("expected message"))
.and_then(String::deserialize)
.map_err(DeError::custom)?;
let errors = match map.contains_key("errors") {
true => map
.remove("errors")
.ok_or_else(|| DeError::custom("expected errors"))
.and_then(deserialize_errors)
.map_err(DeError::custom)?,
false => vec![],
};
Ok(Self {
code,
message,
errors,
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct DiscordJsonSingleError {
pub code: String,
pub message: String,
pub path: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ErrorResponse {
pub status_code: StatusCode,
pub url: Url,
pub error: DiscordJsonError,
}
impl ErrorResponse {
pub async fn from_response(r: Response) -> Self {
ErrorResponse {
status_code: r.status(),
url: r.url().clone(),
error: r.json().await.unwrap_or_else(|_| DiscordJsonError {
code: -1,
message:
"[Serenity] Could not decode json when receiving error response from discord!"
.to_string(),
errors: vec![],
}),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
UnsuccessfulRequest(ErrorResponse),
RateLimitI64F64,
RateLimitUtf8,
Url(UrlError),
InvalidWebhook,
InvalidHeader(InvalidHeaderValue),
Request(ReqwestError),
InvalidScheme,
InvalidPort,
}
impl Error {
pub async fn from_response(r: Response) -> Self {
ErrorResponse::from_response(r).await.into()
}
pub fn is_unsuccessful_request(&self) -> bool {
matches!(self, Self::UnsuccessfulRequest(_))
}
pub fn is_url_error(&self) -> bool {
matches!(self, Self::Url(_))
}
pub fn is_invalid_header(&self) -> bool {
matches!(self, Self::InvalidHeader(_))
}
pub fn status_code(&self) -> Option<StatusCode> {
match self {
Self::UnsuccessfulRequest(res) => Some(res.status_code),
_ => None,
}
}
}
impl From<ErrorResponse> for Error {
fn from(error: ErrorResponse) -> Error {
Error::UnsuccessfulRequest(error)
}
}
impl From<ReqwestError> for Error {
fn from(error: ReqwestError) -> Error {
Error::Request(error)
}
}
impl From<UrlError> for Error {
fn from(error: UrlError) -> Error {
Error::Url(error)
}
}
impl From<InvalidHeaderValue> for Error {
fn from(error: InvalidHeaderValue) -> Error {
Error::InvalidHeader(error)
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
Error::UnsuccessfulRequest(e) => {
f.write_str(&e.error.message)?;
let mut errors_iter = e.error.errors.iter();
if let Some(error) = errors_iter.next() {
f.write_str(" (")?;
f.write_str(&error.path)?;
f.write_str(": ")?;
f.write_str(&error.message)?;
for error in errors_iter {
f.write_str(", ")?;
f.write_str(&error.path)?;
f.write_str(": ")?;
f.write_str(&error.message)?;
}
f.write_str(")")?;
}
Ok(())
},
Error::RateLimitI64F64 => f.write_str("Error decoding a header into an i64 or f64"),
Error::RateLimitUtf8 => f.write_str("Error decoding a header from UTF-8"),
Error::Url(_) => f.write_str("Provided URL is incorrect."),
Error::InvalidWebhook => f.write_str("Provided URL is not a valid webhook."),
Error::InvalidHeader(_) => f.write_str("Provided value is an invalid header value."),
Error::Request(_) => f.write_str("Error while sending HTTP request."),
Error::InvalidScheme => f.write_str("Invalid Url scheme."),
Error::InvalidPort => f.write_str("Invalid port."),
}
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
Error::Url(inner) => Some(inner),
Error::Request(inner) => Some(inner),
_ => None,
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod test {
use http_crate::response::Builder;
use reqwest::ResponseBuilderExt;
use super::*;
#[tokio::test]
async fn test_error_response_into() {
let error = DiscordJsonError {
code: 43121215,
message: String::from("This is a Ferris error"),
errors: vec![],
};
let mut builder = Builder::new();
builder = builder.status(403);
builder = builder.url(String::from("https://ferris.crab").parse().unwrap());
let body_string = serde_json::to_string(&error).unwrap();
let response = builder.body(body_string.into_bytes()).unwrap();
let reqwest_response: reqwest::Response = response.into();
let error_response = ErrorResponse::from_response(reqwest_response).await;
let known = ErrorResponse {
status_code: reqwest::StatusCode::from_u16(403).unwrap(),
url: String::from("https://ferris.crab").parse().unwrap(),
error,
};
assert_eq!(error_response, known);
}
}