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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use crate::models::Permissions;
#[cfg(feature = "client")]
use serde::Deserialize;
use serde::Serialize;
#[cfg(feature = "utoipa")]
use utoipa::ToSchema;
/// A type alias for a [`Result`] with the error type [`Error`].
pub type Result<T> = std::result::Result<T, Error>;
/// The categorization of why the body is malformed.
#[derive(Copy, Clone, Debug, Serialize)]
#[cfg_attr(feature = "client", derive(Deserialize))]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum MalformedBodyErrorType {
/// Invalid content type.
InvalidContentType,
/// Body was invalid UTF-8.
InvalidUtf8,
/// Received invalid JSON body.
InvalidJson,
/// Received invalid multipart body.
InvalidMultipart,
}
/// The type of user interaction that was disallowed.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "client", derive(Deserialize))]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum UserInteractionType {
/// You are unable to open a DM or send DM messages to this user.
Dm,
/// You are unable to add this user to a group DM.
GroupDm,
/// You are unable to request to add this user as a friend.
FriendRequest,
}
impl UserInteractionType {
/// Returns the interaction type as a verb.
#[inline]
#[must_use]
pub const fn as_verb(&self) -> &'static str {
match self {
Self::Dm => "DM",
Self::GroupDm => "add to the group",
Self::FriendRequest => "add as a friend",
}
}
}
/// An error that occurs within Adapt.
#[derive(Clone, Debug, Serialize)]
#[cfg_attr(feature = "client", derive(Deserialize))]
#[cfg_attr(feature = "utoipa", derive(ToSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Error {
/// Received a malformed JSON or MsgPack body.
MalformedBody {
/// Extra information about the error.
error_type: MalformedBodyErrorType,
/// A generalized message about the error.
message: String,
},
/// You are missing the request body in an endpoint that requires it. This is commonly JSON
/// or MsgPack.
MissingBody {
/// The error message.
message: String,
},
/// Invalid field in the request body.
InvalidField {
/// The field that failed validation.
field: String,
/// The error message.
message: String,
},
/// You are missing a required field in the request body.
MissingField {
/// The name of the missing field.
field: String,
/// The error message.
message: String,
},
/// Could not resolve a plausible IP address from the request.
MalformedIp {
/// The error message.
message: String,
},
/// The entity was not found.
NotFound {
/// The type of item that couldn't be found.
entity: String,
/// The error message.
message: String,
},
/// This operation is only allowed in guilds.
GuildOnly {
/// The error message.
message: String,
},
/// Tried authorizing a bot account with anything but an authentication token.
UnsupportedAuthMethod {
/// The error message.
message: String,
},
/// The request required a valid authentication token, but one of the following happened:
///
/// * The token was not provided.
/// * The token was malformed, i.e. a non-UTF-8 string.
/// * The token does not exist or is invalid.
InvalidToken {
/// The error message.
message: String,
},
/// Invalid login credentials were provided, i.e. an invalid password.
InvalidCredentials {
/// Which credential was invalid.
what: String,
/// The error message.
message: String,
},
/// Invalid Turnstile CAPTCHA token was provided. This is a token provided by Cloudflare
/// when a user completes a CAPTCHA, and is used while registering new users to prevent spam.
InvalidCaptcha {
/// The error message.
message: String,
},
/// You must be a member of the guild to perform the requested action.
NotMember {
/// The ID of the guild you are not a member of.
guild_id: u64,
/// The error message.
message: String,
},
/// You must be the owner of the guild to perform the requested action.
NotOwner {
/// The ID of the guild you are not the owner of.
guild_id: u64,
/// The error message.
message: String,
},
/// You must be the owner of the bot to perform the requested action.
NotBotOwner {
/// The ID of the bot you are not the owner of.
bot_id: u64,
/// The error message.
message: String,
},
/// You are not the author of the message you are trying to edit.
NotMessageAuthor {
/// The ID of the message you are trying to edit.
message_id: u64,
/// The error message.
message: String,
},
/// You are too low in the role hierarchy to perform the requested action.
RoleTooLow {
/// The ID of the guild you are not the owner of.
guild_id: u64,
/// The ID of your top role. This is the role you possess with the highest position.
top_role_id: u64,
/// The position of your top role.
top_role_position: u16,
/// The desired position your top role should be in the role hierarchy.
desired_position: u16,
/// The error message.
message: String,
},
/// You are missing the required permissions to perform the requested action.
MissingPermissions {
/// The ID of the guild you are missing permissions in.
guild_id: u64,
/// The permissions required to perform the requested action.
permissions: Permissions,
/// The error message.
message: String,
},
/// You are trying to delete a managed role.
RoleIsManaged {
/// The ID of the guild the role is in.
guild_id: u64,
/// The ID of the role that is managed.
role_id: u64,
/// The error message.
message: String,
},
/// You cannot leave a server or group DM that you are the owner of (you should transfer
/// ownership before leaving).
CannotLeaveAsOwner {
/// The ID of the guild or group DM you are trying to leave.
id: u64,
/// The error message.
message: String,
},
/// You cannot perform the requested action on yourself.
CannotActOnSelf {
/// The error message.
message: String,
},
/// You cannot add bots as friends.
CannotFriendBots {
/// The ID of the bot you are trying to friend.
target_id: u64,
/// The error message.
message: String,
},
/// The user you are trying to interact with (e.g. add as a friend, open DMs, etc.) has privacy
/// settings that prevent you from doing so.
UserInteractionDisallowed {
/// The type of interaction that was disallowed.
interaction_type: UserInteractionType,
/// The ID of the user you are attempting to interact with.
target_id: u64,
/// The error message.
message: String,
},
/// The user has blocked you, so you cannot interact with them.
BlockedByUser {
/// The ID of the user that blocked you.
target_id: u64,
/// The error message.
message: String,
},
/// Something was already taken, e.g. a username or email.
AlreadyTaken {
/// What was already taken.
what: String,
/// The error message.
message: String,
},
/// Something already exists, e.g. a relationship.
AlreadyExists {
/// What already exists.
what: String,
/// The error message.
message: String,
},
/// You are sending requests too quickly are you are being rate limited.
Ratelimited {
/// How long you should wait before sending another request, in whole seconds.
retry_after: f32,
/// The IP address that is being rate limited.
ip: String,
/// The ratelimited message.
message: String,
},
/// Internal server error occured, this is likely a bug.
InternalError {
/// What caused the error. `None` if unknown.
what: Option<String>,
/// The error message.
message: String,
/// A debug version of the error, or `None` if there is no debug version.
debug: Option<String>,
},
}
impl Error {
/// The HTTP status code associated with this error. If this error is not sent over HTTP,
/// this will be `None`.
#[must_use]
pub const fn http_status_code(&self) -> Option<u16> {
Some(match self {
Self::MalformedBody { .. }
| Self::MissingBody { .. }
| Self::InvalidField { .. }
| Self::MissingField { .. }
| Self::MalformedIp { .. }
| Self::UnsupportedAuthMethod { .. }
| Self::CannotActOnSelf { .. }
| Self::CannotFriendBots { .. } => 400,
Self::InvalidToken { .. } | Self::InvalidCredentials { .. } => 401,
Self::GuildOnly { .. }
| Self::NotMember { .. }
| Self::NotOwner { .. }
| Self::NotBotOwner { .. }
| Self::NotMessageAuthor { .. }
| Self::MissingPermissions { .. }
| Self::RoleTooLow { .. }
| Self::RoleIsManaged { .. }
| Self::CannotLeaveAsOwner { .. }
| Self::UserInteractionDisallowed { .. }
| Self::BlockedByUser { .. }
| Self::InvalidCaptcha { .. } => 403,
Self::NotFound { .. } => 404,
Self::AlreadyTaken { .. } | Self::AlreadyExists { .. } => 409,
Self::Ratelimited { .. } => 429,
Self::InternalError { .. } => 500,
})
}
/// Returns an internal error with the given message.
#[must_use]
pub fn custom(message: impl AsRef<str>) -> Self {
Self::InternalError {
what: None,
message: message.as_ref().to_string(),
debug: None,
}
}
/// Returns an internal error with the given "what" and message.
#[must_use]
pub fn custom_for(what: impl AsRef<str>, message: impl AsRef<str>) -> Self {
Self::InternalError {
what: Some(what.as_ref().to_string()),
message: message.as_ref().to_string(),
debug: None,
}
}
}
#[cfg(feature = "db")]
impl From<sqlx::Error> for Error {
fn from(e: sqlx::Error) -> Self {
Self::InternalError {
what: Some("database".to_string()),
message: e.to_string(),
debug: Some(format!("{e:?}")),
}
}
}
#[cfg(feature = "db")]
impl From<deadpool_redis::redis::RedisError> for Error {
fn from(e: deadpool_redis::redis::RedisError) -> Self {
Self::InternalError {
what: Some("cache".to_string()),
message: e.to_string(),
debug: Some(format!("{e:?}")),
}
}
}
#[cfg(feature = "db")]
impl From<deadpool_redis::PoolError> for Error {
fn from(e: deadpool_redis::PoolError) -> Self {
Self::InternalError {
what: Some("cache".to_string()),
message: e.to_string(),
debug: Some(format!("{e:?}")),
}
}
}
#[cfg(feature = "db")]
impl From<bincode::error::EncodeError> for Error {
fn from(e: bincode::error::EncodeError) -> Self {
Self::InternalError {
what: Some("bincode_encode".to_string()),
message: e.to_string(),
debug: Some(format!("{e:?}")),
}
}
}
#[cfg(feature = "db")]
impl From<bincode::error::DecodeError> for Error {
fn from(e: bincode::error::DecodeError) -> Self {
Self::InternalError {
what: Some("bincode_decode".to_string()),
message: e.to_string(),
debug: Some(format!("{e:?}")),
}
}
}
#[cfg(feature = "auth")]
impl From<argon2_async::Error> for Error {
fn from(e: argon2_async::Error) -> Self {
Self::InternalError {
what: Some("hasher".to_string()),
message: e.to_string(),
debug: Some(format!("{e:?}")),
}
}
}
/// An extension trait for [`Option`] that adds [`NotFoundExt::ok_or_not_found`].
pub trait NotFoundExt<T> {
/// Converts an [`Option`] to a [`Result`] with [`Error::NotFound`] if it is [`None`].
///
/// # Example
/// ```no_run
/// use essence::error::NotFoundExt;
///
/// assert_eq!(Some(5).ok_or_not_found("user", "user not found"), Ok(5));
/// ```
fn ok_or_not_found(self, entity: impl ToString, message: impl ToString) -> Result<T>;
}
impl<T> NotFoundExt<T> for Option<T> {
#[inline]
fn ok_or_not_found(self, entity: impl ToString, message: impl ToString) -> Result<T> {
self.ok_or_else(|| Error::NotFound {
entity: entity.to_string(),
message: message.to_string(),
})
}
}
/// An extension trait for [`std::result::Result`] that adds [`ErrIntoExt::err_into`].
pub trait ErrIntoExt<T, E, F> {
/// Converts a [`std::result::Result<T, E>`] into a [`std::result::Result<T, F>`] `
/// where `F: From<E>` using [`Into::into`]
fn err_into(self) -> std::result::Result<T, F>;
}
impl<T, E, F: From<E>> ErrIntoExt<T, E, F> for std::result::Result<T, E> {
fn err_into(self) -> std::result::Result<T, F> {
self.map_err(Into::into)
}
}