serenity/model/error.rs
1//! Error enum definition wrapping potential model implementation errors.
2
3use std::error::Error as StdError;
4use std::fmt;
5
6use super::Permissions;
7
8/// An error returned from the [`model`] module.
9///
10/// This is always wrapped within the library's [`Error::Model`] variant.
11///
12/// # Examples
13///
14/// Matching an [`Error`] with this variant would look something like the following for the
15/// [`GuildId::ban`] method, which in this example is used to re-ban all members.
16///
17/// ```rust,no_run
18/// use serenity::model::prelude::*;
19/// use serenity::model::ModelError;
20/// use serenity::prelude::*;
21/// use serenity::Error;
22///
23/// # struct Handler;
24///
25/// #[serenity::async_trait]
26/// #[cfg(feature = "client")]
27/// impl EventHandler for Handler {
28/// async fn guild_ban_removal(&self, context: Context, guild_id: GuildId, user: User) {
29/// match guild_id.ban(&context, user, 8).await {
30/// Ok(()) => {
31/// // Ban successful.
32/// },
33/// Err(Error::Model(ModelError::DeleteMessageDaysAmount(amount))) => {
34/// println!("Failed deleting {} days' worth of messages", amount);
35/// },
36/// Err(why) => {
37/// println!("Unexpected error: {:?}", why);
38/// },
39/// }
40/// }
41/// }
42/// ```
43///
44/// [`Error`]: crate::Error
45/// [`Error::Model`]: crate::Error::Model
46/// [`GuildId::ban`]: super::id::GuildId::ban
47/// [`model`]: crate::model
48#[derive(Clone, Debug, Eq, Hash, PartialEq)]
49#[non_exhaustive]
50pub enum Error {
51 /// When attempting to delete below or above the minimum or maximum allowed number of messages.
52 BulkDeleteAmount,
53 /// When attempting to delete a number of days' worth of messages that is not allowed.
54 DeleteMessageDaysAmount(u8),
55 /// When attempting to send a message with over 10 embeds.
56 EmbedAmount,
57 /// Indicates that the textual content of an embed exceeds the maximum length.
58 EmbedTooLarge(usize),
59 /// An indication that a [`Guild`] could not be found by [Id][`GuildId`] in the [`Cache`].
60 ///
61 /// [`Guild`]: super::guild::Guild
62 /// [`GuildId`]: super::id::GuildId
63 /// [`Cache`]: crate::cache::Cache
64 GuildNotFound,
65 /// An indication that a [`Role`] could not be found by [Id][`RoleId`] in the [`Cache`].
66 ///
67 /// [`Role`]: super::guild::Role
68 /// [`RoleId`]: super::id::RoleId
69 /// [`Cache`]: crate::cache::Cache
70 RoleNotFound,
71 /// An indication that a [`Member`] could not be found by [Id][`UserId`] in the [`Cache`].
72 ///
73 /// [`Member`]: super::guild::Member
74 /// [`UserId`]: super::id::UserId
75 /// [`Cache`]: crate::cache::Cache
76 MemberNotFound,
77 /// An indication that a [`Channel`] could not be found by [Id][`ChannelId`] in the [`Cache`].
78 ///
79 /// [`Channel`]: super::channel::Channel
80 /// [`ChannelId`]: super::id::ChannelId
81 /// [`Cache`]: crate::cache::Cache
82 ChannelNotFound,
83 /// An indication that a [`Message`] has already been crossposted, and cannot be crossposted
84 /// twice.
85 ///
86 /// [`Message`]: super::channel::Message
87 MessageAlreadyCrossposted,
88 /// An indication that you cannot crosspost a [`Message`].
89 ///
90 /// For instance, you cannot crosspost a system message or a message coming from the crosspost
91 /// feature.
92 ///
93 /// [`Message`]: super::channel::Message
94 CannotCrosspostMessage,
95 /// Indicates that there are hierarchy problems restricting an action.
96 ///
97 /// For example, when banning a user, if the other user has a role with an equal to or higher
98 /// position, then they can not be banned.
99 ///
100 /// When editing a role, if the role is higher in position than the current user's highest
101 /// role, then the role can not be edited.
102 Hierarchy,
103 /// Indicates that you do not have the required permissions to perform an operation.
104 InvalidPermissions {
105 /// Which permissions were required for the operation
106 required: Permissions,
107 /// Which permissions the bot had
108 present: Permissions,
109 },
110 /// An indicator that the [current user] cannot perform an action.
111 ///
112 /// [current user]: super::user::CurrentUser
113 InvalidUser,
114 /// An indicator that an item is missing from the [`Cache`], and the action can not be
115 /// continued.
116 ///
117 /// [`Cache`]: crate::cache::Cache
118 ItemMissing,
119 /// Indicates that a member, role or channel from the wrong [`Guild`] was provided.
120 ///
121 /// [`Guild`]: super::guild::Guild
122 WrongGuild,
123 /// Indicates that a [`Message`]s content was too long and will not successfully send, as the
124 /// length is over 2000 codepoints.
125 ///
126 /// The number of code points larger than the limit is provided.
127 ///
128 /// [`Message`]: super::channel::Message
129 MessageTooLong(usize),
130 /// Indicates that the current user is attempting to Direct Message another bot user, which is
131 /// disallowed by the API.
132 MessagingBot,
133 /// An indicator that the [`ChannelType`] cannot perform an action.
134 ///
135 /// [`ChannelType`]: super::channel::ChannelType
136 InvalidChannelType,
137 /// Indicates that the webhook name is under the 2 characters limit.
138 NameTooShort,
139 /// Indicates that the webhook name is over the 100 characters limit.
140 NameTooLong,
141 /// Indicates that the bot is not author of the message. This error is returned in
142 /// private/direct channels.
143 NotAuthor,
144 /// Indicates that the webhook token is missing.
145 NoTokenSet,
146 /// When attempting to delete a built in nitro sticker instead of a guild sticker.
147 DeleteNitroSticker,
148 /// Indicates that the sticker file is missing.
149 NoStickerFileSet,
150 /// When attempting to send a message with over 3 stickers.
151 StickerAmount,
152 /// When attempting to edit a voice message.
153 CannotEditVoiceMessage,
154}
155
156impl Error {
157 /// Return `true` if the model error is related to an item missing in the cache.
158 #[must_use]
159 pub const fn is_cache_err(&self) -> bool {
160 matches!(
161 self,
162 Self::ItemMissing
163 | Self::ChannelNotFound
164 | Self::RoleNotFound
165 | Self::GuildNotFound
166 | Self::MemberNotFound
167 )
168 }
169}
170
171impl fmt::Display for Error {
172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173 match self {
174 Self::BulkDeleteAmount => f.write_str("Too few/many messages to bulk delete."),
175 Self::DeleteMessageDaysAmount(_) => f.write_str("Invalid delete message days."),
176 Self::EmbedAmount => f.write_str("Too many embeds in a message."),
177 Self::EmbedTooLarge(_) => f.write_str("Embed too large."),
178 Self::GuildNotFound => f.write_str("Guild not found in the cache."),
179 Self::RoleNotFound => f.write_str("Role not found in the cache."),
180 Self::MemberNotFound => f.write_str("Member not found in the cache."),
181 Self::ChannelNotFound => f.write_str("Channel not found in the cache."),
182 Self::Hierarchy => f.write_str("Role hierarchy prevents this action."),
183 Self::InvalidChannelType => f.write_str("The channel cannot perform the action."),
184 Self::InvalidPermissions {
185 ..
186 } => f.write_str("Invalid permissions."),
187 Self::InvalidUser => f.write_str("The current user cannot perform the action."),
188 Self::ItemMissing => f.write_str("The required item is missing from the cache."),
189 Self::WrongGuild => f.write_str("Provided member or channel is from the wrong guild."),
190 Self::MessageTooLong(_) => f.write_str("Message too large."),
191 Self::MessageAlreadyCrossposted => f.write_str("Message already crossposted."),
192 Self::CannotCrosspostMessage => f.write_str("Cannot crosspost this message type."),
193 Self::MessagingBot => f.write_str("Attempted to message another bot user."),
194 Self::NameTooShort => f.write_str("Name is under the character limit."),
195 Self::NameTooLong => f.write_str("Name is over the character limit."),
196 Self::NotAuthor => f.write_str("The bot is not author of this message."),
197 Self::NoTokenSet => f.write_str("Token is not set."),
198 Self::DeleteNitroSticker => f.write_str("Cannot delete an official sticker."),
199 Self::NoStickerFileSet => f.write_str("Sticker file is not set."),
200 Self::StickerAmount => f.write_str("Too many stickers in a message."),
201 Self::CannotEditVoiceMessage => f.write_str("Cannot edit voice message."),
202 }
203 }
204}
205
206impl StdError for Error {}