teloxide_core/errors.rs
1//! Possible error types.
2
3use std::{fmt, io, sync::Arc};
4
5use thiserror::Error;
6
7use crate::types::{ChatId, ResponseParameters, Seconds};
8
9/// An error caused by sending a request to Telegram.
10#[derive(Debug, Error, Clone)]
11pub enum RequestError {
12 /// A Telegram API error.
13 #[error("A Telegram's error: {0}")]
14 Api(#[from] ApiError),
15
16 /// The group has been migrated to a supergroup with the specified
17 /// identifier.
18 #[error("The group has been migrated to a supergroup with ID #{0}")]
19 MigrateToChatId(ChatId),
20
21 /// In case of exceeding flood control, the number of seconds left to wait
22 /// before the request can be repeated.
23 #[error("Retry after {0}")]
24 RetryAfter(Seconds),
25
26 /// Network error while sending a request to Telegram.
27 #[error("A network error: {0}")]
28 // NOTE: this variant must not be created by anything except the explicit From impl
29 Network(#[source] Arc<reqwest::Error>),
30
31 /// Error while parsing a response from Telegram.
32 ///
33 /// If you've received this error, please, [open an issue] with the
34 /// description of the error.
35 ///
36 /// [open an issue]: https://github.com/teloxide/teloxide/issues/new
37 #[error(transparent)]
38 InvalidJson(InvalidJson),
39
40 /// The throttling worker stopped before sending the request.
41 #[error("The throttle worker stopped")]
42 ThrottleWorkerStopped,
43
44 /// The global or per-chat throttling queue could not admit the request.
45 #[error("The throttle queue is full")]
46 ThrottleQueueFull,
47
48 /// Occurs when trying to send a file to Telegram.
49 #[error("An I/O error: {0}")]
50 Io(#[from] Arc<io::Error>),
51}
52
53/// A JSON response that could not be deserialized.
54#[derive(Clone)]
55pub struct InvalidJson {
56 line: usize,
57 column: usize,
58 raw_preview: Arc<str>,
59}
60
61impl InvalidJson {
62 pub(crate) fn new(source: serde_json::Error, mut raw: String) -> Self {
63 const MAX_BYTES: usize = 1024;
64 let mut end = raw.len().min(MAX_BYTES);
65 while !raw.is_char_boundary(end) {
66 end -= 1;
67 }
68 raw.truncate(end);
69 Self { line: source.line(), column: source.column(), raw_preview: raw.into() }
70 }
71
72 /// Returns up to the first 1024 bytes of the raw response, at a UTF-8
73 /// boundary. This data can contain secrets and should not be logged
74 /// indiscriminately.
75 #[must_use]
76 pub fn raw_preview(&self) -> &str {
77 &self.raw_preview
78 }
79}
80
81impl fmt::Display for InvalidJson {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(f, "An error while parsing JSON at line {} column {}", self.line, self.column)
84 }
85}
86
87impl fmt::Debug for InvalidJson {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 fmt::Display::fmt(self, f)
90 }
91}
92
93// A serde error can itself contain data from the response; do not expose it in
94// the error chain traversed by loggers.
95impl std::error::Error for InvalidJson {}
96
97/// An error caused by downloading a file.
98#[derive(Debug, Error, Clone)]
99pub enum DownloadError {
100 /// A network error while downloading a file from Telegram.
101 #[error("A network error: {0}")]
102 // NOTE: this variant must not be created by anything except the explicit From impl
103 Network(#[source] Arc<reqwest::Error>),
104
105 /// An I/O error while writing a file to destination.
106 #[error("An I/O error: {0}")]
107 Io(#[from] Arc<std::io::Error>),
108}
109
110pub trait AsResponseParameters {
111 fn response_parameters(&self) -> Option<ResponseParameters>;
112
113 /// Whether Telegram explicitly refused the request, rather than its outcome
114 /// being unknown. Custom requester errors can override the conservative
115 /// default.
116 fn is_api_refusal(&self) -> bool {
117 false
118 }
119
120 fn retry_after(&self) -> Option<Seconds> {
121 self.response_parameters().and_then(|rp| match rp {
122 ResponseParameters::RetryAfter(n) => Some(n),
123 _ => None,
124 })
125 }
126
127 fn migrate_to_chat_id(&self) -> Option<ChatId> {
128 self.response_parameters().and_then(|rp| match rp {
129 ResponseParameters::MigrateToChatId(id) => Some(id),
130 _ => None,
131 })
132 }
133}
134
135impl AsResponseParameters for crate::RequestError {
136 fn is_api_refusal(&self) -> bool {
137 matches!(self, Self::Api(_) | Self::MigrateToChatId(_) | Self::RetryAfter(_))
138 }
139
140 fn response_parameters(&self) -> Option<ResponseParameters> {
141 match *self {
142 Self::RetryAfter(n) => Some(ResponseParameters::RetryAfter(n)),
143 Self::MigrateToChatId(id) => Some(ResponseParameters::MigrateToChatId(id)),
144 _ => None,
145 }
146 }
147}
148
149macro_rules! impl_api_error {
150 (
151 $( #[$meta:meta] )*
152 $vis:vis enum $ident:ident {
153 $(
154 $( #[$var_meta:meta] )*
155 $var_name:ident $( ($var_inner:ty) )? = $var_string:literal $(with $var_parser:expr)?
156 ),*
157 }
158 ) => {
159
160 $(#[$meta])*
161 #[derive(Error)]
162 $vis enum $ident {
163 $(
164 $(#[$var_meta])*
165 #[error($var_string)]
166 $var_name $(($var_inner))*,
167 )*
168 }
169
170 const _: () = {
171 struct Visitor;
172
173 impl<'de> ::serde::de::Visitor<'de> for Visitor {
174 type Value = $ident;
175
176 fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
177 formatter.write_str("telegram api error string")
178 }
179
180 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
181 where
182 E: ::serde::de::Error,
183 {
184 $(impl_api_error!(@de v, $var_name $( ($var_inner) )?, $var_string $(, $var_parser)*);)*
185 Err(E::unknown_variant(v, &[]))
186 }
187 }
188
189 impl<'de> ::serde::de::Deserialize<'de> for $ident {
190 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
191 where
192 D: ::serde::de::Deserializer<'de>,
193 {
194 deserializer.deserialize_str(Visitor)
195 }
196 }
197 };
198 };
199 (@de $value:ident, $variant:ident, $val:literal) => {
200 if $value == $val {
201 return Ok(Self::Value::$variant)
202 }
203 };
204 (@de $value:ident, $variant:ident ($var_inner:ty), $val:literal, $block:expr) => {
205 #[allow(clippy::redundant_closure_call)]
206 match $block($value) {
207 Some(data) => return Ok(Self::Value::$variant(data)),
208 _ => {}
209 }
210 };
211 (@de $value:ident, $variant:ident, $val:literal, $block:expr) => {
212 #[allow(clippy::redundant_closure_call)]
213 if $block($value) {
214 return Ok(Self::Value::$variant);
215 }
216 };
217}
218
219impl_api_error! {
220 /// A kind of an API error.
221 #[derive(Debug, PartialEq, Hash, Eq, Clone)]
222 #[non_exhaustive]
223 pub enum ApiError {
224 /// Occurs when the bot tries to send message to user who blocked the bot.
225 BotBlocked = "Forbidden: bot was blocked by the user",
226
227 /// Occurs when the bot token is invalid.
228 // N.B. These errors are actually slightly different, "Unauthorized" is when the bot token
229 // is formatted mostly right, but is incorrect, whereas "Not Found" is when the url is
230 // not handled by TBA at all. From user POV both of those are "token is invalid", but
231 // there might be some cases where this is not right...
232 InvalidToken = "Invalid bot token" with |text: &str| text == "Unauthorized" || text == "Not Found",
233
234 /// Occurs when bot tries to modify a message without modification content.
235 ///
236 /// May happen in methods:
237 /// 1. [`EditMessageText`]
238 ///
239 /// [`EditMessageText`]: crate::payloads::EditMessageText
240 MessageNotModified = "Bad Request: message is not modified: specified new message content and reply markup are \
241 exactly the same as a current content and reply markup of the message",
242
243 /// Occurs when bot tries to forward or delete a message which was deleted.
244 ///
245 /// May happen in methods:
246 /// 1. [`ForwardMessage`]
247 /// 2. [`DeleteMessage`]
248 ///
249 /// [`ForwardMessage`]: crate::payloads::ForwardMessage
250 /// [`DeleteMessage`]: crate::payloads::DeleteMessage
251 MessageIdInvalid = "Bad Request: MESSAGE_ID_INVALID",
252
253 /// Occurs when bot tries to forward a message which does not exists.
254 ///
255 /// May happen in methods:
256 /// 1. [`ForwardMessage`]
257 ///
258 /// [`ForwardMessage`]: crate::payloads::ForwardMessage
259 MessageToForwardNotFound = "Bad Request: message to forward not found",
260
261 /// Occurs when bot tries to delete a message which does not exists.
262 ///
263 /// May happen in methods:
264 /// 1. [`DeleteMessage`]
265 ///
266 /// [`DeleteMessage`]: crate::payloads::DeleteMessage
267 MessageToDeleteNotFound = "Bad Request: message to delete not found",
268
269 /// Occurs when bot tries to copy a message which does not exists.
270 /// May happen in methods:
271 /// 1. [`CopyMessage`]
272 ///
273 /// [`CopyMessage`]: crate::payloads::CopyMessage
274 MessageToCopyNotFound = "Bad Request: message to copy not found",
275
276 /// Occurs when bot tries to send a text message without text.
277 ///
278 /// May happen in methods:
279 /// 1. [`SendMessage`]
280 ///
281 /// [`SendMessage`]: crate::payloads::SendMessage
282 MessageTextIsEmpty = "Bad Request: message text is empty",
283
284 /// Occurs when bot tries to edit a message after long time.
285 ///
286 /// May happen in methods:
287 /// 1. [`EditMessageText`]
288 ///
289 /// [`EditMessageText`]: crate::payloads::EditMessageText
290 MessageCantBeEdited = "Bad Request: message can't be edited",
291
292 /// Occurs when bot tries to delete a someone else's message in group where
293 /// it does not have enough rights.
294 ///
295 /// May happen in methods:
296 /// 1. [`DeleteMessage`]
297 ///
298 /// [`DeleteMessage`]: crate::payloads::DeleteMessage
299 MessageCantBeDeleted = "Bad Request: message can't be deleted",
300
301 /// Occurs when bot tries to edit a message which does not exists.
302 ///
303 /// May happen in methods:
304 /// 1. [`EditMessageText`]
305 ///
306 /// [`EditMessageText`]: crate::payloads::EditMessageText
307 MessageToEditNotFound = "Bad Request: message to edit not found",
308
309 /// Occurs when bot tries to edit a message which has no text.
310 ///
311 /// May happen in methods:
312 /// 1. [`EditMessageText`]
313 /// 2. [`EditMessageTextInline`]
314 ///
315 /// [`EditMessageText`]: crate::payloads::EditMessageText
316 /// [`EditMessageTextInline`]: crate::payloads::EditMessageTextInline
317 MessageToEditHasNoText = "Bad Request: there is no text in the message to edit",
318
319 /// Occurs when bot tries to reply to a message which does not exists.
320 ///
321 /// May happen in methods:
322 /// 1. [`SendMessage`]
323 ///
324 /// [`SendMessage`]: crate::payloads::SendMessage
325 MessageToReplyNotFound = "Bad Request: message to be replied not found",
326
327 /// Occurs when bot tries to
328 MessageIdentifierNotSpecified = "Bad Request: message identifier is not specified",
329
330 /// Occurs when bot tries to send a message with text size greater then
331 /// 4096 symbols.
332 ///
333 /// May happen in methods:
334 /// 1. [`SendMessage`]
335 ///
336 /// [`SendMessage`]: crate::payloads::SendMessage
337 MessageIsTooLong = "Bad Request: message is too long",
338
339 /// Occurs when bot tries to edit a message with text size greater then
340 /// 4096 symbols.
341 ///
342 /// May happen in methods:
343 /// 1. [`EditMessageText`]
344 /// 2. [`EditMessageTextInline`]
345 /// 3. [`EditMessageCaption`]
346 /// 4. [`EditMessageCaptionInline`]
347 ///
348 /// [`EditMessageText`]: crate::payloads::EditMessageText
349 /// [`EditMessageTextInline`]: crate::payloads::EditMessageTextInline
350 /// [`EditMessageCaption`]: crate::payloads::EditMessageCaption
351 /// [`EditMessageCaptionInline`]: crate::payloads::EditMessageCaptionInline
352 EditedMessageIsTooLong = "Bad Request: MESSAGE_TOO_LONG",
353
354 /// Occurs when bot tries to send media group with more than 10 items.
355 ///
356 /// May happen in methods:
357 /// 1. [`SendMediaGroup`]
358 ///
359 /// [`SendMediaGroup`]: crate::payloads::SendMediaGroup
360 TooMuchMessages = "Bad Request: Too much messages to send as an album",
361
362 /// Occurs when bot tries to answer an inline query with more than 50
363 /// results.
364 ///
365 /// Consider using offsets to paginate results.
366 ///
367 /// May happen in methods:
368 /// 1. [`AnswerInlineQuery`]
369 ///
370 /// [`AnswerInlineQuery`]: crate::payloads::AnswerInlineQuery
371 TooMuchInlineQueryResults = "Bad Request: RESULTS_TOO_MUCH",
372
373 /// Occurs when bot tries to stop poll that has already been stopped.
374 ///
375 /// May happen in methods:
376 /// 1. [`SendPoll`]
377 ///
378 /// [`SendPoll`]: crate::payloads::SendPoll
379 PollHasAlreadyClosed = "Bad Request: poll has already been closed",
380
381 /// Occurs when bot tries to send poll with less than 2 options.
382 ///
383 /// May happen in methods:
384 /// 1. [`SendPoll`]
385 ///
386 /// [`SendPoll`]: crate::payloads::SendPoll
387 PollMustHaveMoreOptions = "Bad Request: poll must have at least 2 option",
388
389 /// Occurs when bot tries to send poll with more than 12 options.
390 ///
391 /// May happen in methods:
392 /// 1. [`SendPoll`]
393 ///
394 /// [`SendPoll`]: crate::payloads::SendPoll
395 PollCantHaveMoreOptions = "Bad Request: poll can't have more than 12 options",
396
397 /// Occurs when bot tries to send poll with empty option (without text).
398 ///
399 /// May happen in methods:
400 /// 1. [`SendPoll`]
401 ///
402 /// [`SendPoll`]: crate::payloads::SendPoll
403 PollOptionsMustBeNonEmpty = "Bad Request: poll options must be non-empty",
404
405 /// Occurs when bot tries to send poll with empty question (without text).
406 ///
407 /// May happen in methods:
408 /// 1. [`SendPoll`]
409 ///
410 /// [`SendPoll`]: crate::payloads::SendPoll
411 PollQuestionMustBeNonEmpty = "Bad Request: poll question must be non-empty",
412
413 /// Occurs when bot tries to send poll with total size of options more than
414 /// 100 symbols.
415 ///
416 /// May happen in methods:
417 /// 1. [`SendPoll`]
418 ///
419 /// [`SendPoll`]: crate::payloads::SendPoll
420 PollOptionsLengthTooLong = "Bad Request: poll options length must not exceed 100",
421
422 /// Occurs when bot tries to send poll with question size more than 255
423 /// symbols.
424 ///
425 /// May happen in methods:
426 /// 1. [`SendPoll`]
427 ///
428 /// [`SendPoll`]: crate::payloads::SendPoll
429 PollQuestionLengthTooLong = "Bad Request: poll question length must not exceed 255",
430
431 /// Occurs when bot tries to stop poll with message without poll.
432 ///
433 /// May happen in methods:
434 /// 1. [`StopPoll`]
435 ///
436 /// [`StopPoll`]: crate::payloads::StopPoll
437 MessageWithPollNotFound = "Bad Request: message with poll to stop not found",
438
439 /// Occurs when bot tries to stop poll with message without poll.
440 ///
441 /// May happen in methods:
442 /// 1. [`StopPoll`]
443 ///
444 /// [`StopPoll`]: crate::payloads::StopPoll
445 MessageIsNotAPoll = "Bad Request: message is not a poll",
446
447 /// Occurs when bot tries to send a message to chat in which it is not a
448 /// member.
449 ///
450 /// May happen in methods:
451 /// 1. [`SendMessage`]
452 ///
453 /// [`SendMessage`]: crate::payloads::SendMessage
454 ChatNotFound = "Bad Request: chat not found",
455
456 /// Occurs when bot tries to send method with unknown user_id.
457 ///
458 /// May happen in methods:
459 /// 1. [`getUserProfilePhotos`]
460 ///
461 /// [`getUserProfilePhotos`]:
462 /// crate::payloads::GetUserProfilePhotos
463 UserNotFound = "Bad Request: user not found",
464
465 /// Occurs when bot tries to send [`SetChatDescription`] with same text as
466 /// in the current description.
467 ///
468 /// May happen in methods:
469 /// 1. [`SetChatDescription`]
470 ///
471 /// [`SetChatDescription`]: crate::payloads::SetChatDescription
472 ChatDescriptionIsNotModified = "Bad Request: chat description is not modified",
473
474 /// Occurs when bot tries to answer to query after timeout expire.
475 ///
476 /// May happen in methods:
477 /// 1. [`AnswerCallbackQuery`]
478 ///
479 /// [`AnswerCallbackQuery`]: crate::payloads::AnswerCallbackQuery
480 InvalidQueryId = "Bad Request: query is too old and response timeout expired or query id is invalid",
481
482 /// Occurs when bot tries to send InlineKeyboardMarkup with invalid button
483 /// url.
484 ///
485 /// May happen in methods:
486 /// 1. [`SendMessage`]
487 ///
488 /// [`SendMessage`]: crate::payloads::SendMessage
489 ButtonUrlInvalid = "Bad Request: BUTTON_URL_INVALID",
490
491 /// Occurs when bot tries to send button with data size more than 64 bytes.
492 ///
493 /// May happen in methods:
494 /// 1. [`SendMessage`]
495 ///
496 /// [`SendMessage`]: crate::payloads::SendMessage
497 ButtonDataInvalid = "Bad Request: BUTTON_DATA_INVALID",
498
499 /// Occurs when bot tries to send button with data size == 0.
500 ///
501 /// May happen in methods:
502 /// 1. [`SendMessage`]
503 ///
504 /// [`SendMessage`]: crate::payloads::SendMessage
505 TextButtonsAreUnallowed = "Bad Request: can't parse inline keyboard button: Text buttons are unallowed in the \
506 inline keyboard",
507
508 /// Occurs when bot tries to get file by wrong file id.
509 ///
510 /// May happen in methods:
511 /// 1. [`GetFile`]
512 ///
513 /// [`GetFile`]: crate::payloads::GetFile
514 WrongFileId = "Bad Request: wrong file id",
515
516 /// Occurs when bot tries to send files with wrong file identifier or HTTP
517 /// url
518 WrongFileIdOrUrl = "Bad Request: wrong file identifier/HTTP URL specified",
519
520 /// Occurs when When sending files with an url to a site that doesn't
521 /// respond.
522 FailedToGetUrlContent = "Bad Request: failed to get HTTP URL content",
523
524 /// Occurs when bot tries to do some with group which was deactivated.
525 GroupDeactivated = "Bad Request: group is deactivated",
526
527 /// Occurs when image processing fails on telegram's side.
528 ///
529 /// This is likely caused by an incorrectly encoded image, make sure that
530 /// the image is correctly encoded in a format telegram accepts.
531 ImageProcessFailed = "Bad Request: IMAGE_PROCESS_FAILED",
532
533 /// Occurs when bot tries to set chat photo from file ID
534 ///
535 /// May happen in methods:
536 /// 1. [`SetChatPhoto`]
537 ///
538 /// [`SetChatPhoto`]: crate::payloads::SetChatPhoto
539 PhotoAsInputFileRequired = "Bad Request: Photo should be uploaded as an InputFile",
540
541 /// Occurs when bot tries to add sticker to stickerset by invalid name.
542 ///
543 /// May happen in methods:
544 /// 1. [`AddStickerToSet`]
545 ///
546 /// [`AddStickerToSet`]: crate::payloads::AddStickerToSet
547 InvalidStickersSet = "Bad Request: STICKERSET_INVALID",
548
549 /// Occurs when bot tries to create a sticker set with a name that is
550 /// already used by another sticker set.
551 ///
552 /// May happen in methods:
553 /// 1. [`CreateNewStickerSet`]
554 ///
555 /// [`CreateNewStickerSet`]: crate::payloads::CreateNewStickerSet
556 StickerSetNameOccupied = "Bad Request: sticker set name is already occupied",
557
558 /// Occurs when bot tries to create a sticker set with user id of a bot.
559 ///
560 /// May happen in methods:
561 /// 1. [`CreateNewStickerSet`]
562 ///
563 /// [`CreateNewStickerSet`]: crate::payloads::CreateNewStickerSet
564 StickerSetOwnerIsBot = "Bad Request: USER_IS_BOT",
565
566 /// Occurs when bot tries to create a sticker set with invalid name.
567 ///
568 /// From documentation of [`CreateNewStickerSet`]:
569 /// > Short name of sticker set, to be used in `t.me/addstickers/` URLs
570 /// (e.g., _animals_). Can contain only english letters, digits and
571 /// underscores. Must begin with a letter, can't contain consecutive
572 /// underscores and must end in “\_by\_<bot\_username>”. <bot\_username>
573 /// is case insensitive. 1-64 characters.
574 ///
575 /// May happen in methods:
576 /// 1. [`CreateNewStickerSet`]
577 ///
578 /// [`CreateNewStickerSet`]: crate::payloads::CreateNewStickerSet
579 InvalidStickerName = "Bad Request: invalid sticker set name is specified",
580
581 /// Occurs when bot tries to pin a message without rights to pin in this
582 /// chat.
583 ///
584 /// May happen in methods:
585 /// 1. [`PinChatMessage`]
586 ///
587 /// [`PinChatMessage`]: crate::payloads::PinChatMessage
588 NotEnoughRightsToPinMessage = "Bad Request: not enough rights to pin a message",
589
590 /// Occurs when bot tries to pin or unpin a message without rights to pin
591 /// in this chat.
592 ///
593 /// May happen in methods:
594 /// 1. [`PinChatMessage`]
595 /// 2. [`UnpinChatMessage`]
596 ///
597 /// [`PinChatMessage`]: crate::payloads::PinChatMessage
598 /// [`UnpinChatMessage`]: crate::payloads::UnpinChatMessage
599 NotEnoughRightsToManagePins = "Bad Request: not enough rights to manage pinned messages in the chat",
600
601 /// Occurs when bot tries change default chat permissions without "Ban
602 /// Users" permission in this chat.
603 ///
604 /// May happen in methods:
605 /// 1. [`SetChatPermissions`]
606 ///
607 /// [`SetChatPermissions`]: crate::payloads::SetChatPermissions
608 NotEnoughRightsToChangeChatPermissions = "Bad Request: not enough rights to change chat permissions",
609
610 /// Occurs when bot tries to use method in group which is allowed only in a
611 /// supergroup or channel.
612 MethodNotAvailableInPrivateChats = "Bad Request: method is available only for supergroups and channel",
613
614 /// Occurs when bot tries to demote chat creator.
615 ///
616 /// May happen in methods:
617 /// 1. [`PromoteChatMember`]
618 ///
619 /// [`PromoteChatMember`]: crate::payloads::PromoteChatMember
620 CantDemoteChatCreator = "Bad Request: can't demote chat creator",
621
622 /// Occurs when bot tries to restrict self in group chats.
623 ///
624 /// May happen in methods:
625 /// 1. [`RestrictChatMember`]
626 ///
627 /// [`RestrictChatMember`]: crate::payloads::RestrictChatMember
628 CantRestrictSelf = "Bad Request: can't restrict self",
629
630 /// Occurs when bot tries to restrict chat member without rights to
631 /// restrict in this chat.
632 ///
633 /// May happen in methods:
634 /// 1. [`RestrictChatMember`]
635 ///
636 /// [`RestrictChatMember`]: crate::payloads::RestrictChatMember
637 NotEnoughRightsToRestrict = "Bad Request: not enough rights to restrict/unrestrict chat member",
638
639 /// Occurs when bot tries to post a message in a channel without "Post
640 /// Messages" admin right.
641 NotEnoughRightsToPostMessages = "Bad Request: need administrator rights in the channel chat",
642
643 /// Occurs when bot tries to get a chat member with an invalid
644 /// participant ID.
645 ///
646 /// May happen in methods:
647 /// 1. [`GetChatMember`]
648 ///
649 /// [`GetChatMember`]: crate::payloads::GetChatMember
650 ParticipantIdInvalid = "Bad Request: PARTICIPANT_ID_INVALID",
651
652 /// Occurs when bot tries to perform an action that requires admin
653 /// privileges in the chat.
654 ///
655 /// May happen in methods:
656 /// 1. [`GetChatMember`]
657 ///
658 /// [`GetChatMember`]: crate::payloads::GetChatMember
659 ChatAdminRequired = "Bad Request: CHAT_ADMIN_REQUIRED",
660
661 /// Occurs when bot tries set webhook to protocol other than HTTPS.
662 ///
663 /// May happen in methods:
664 /// 1. [`SetWebhook`]
665 ///
666 /// [`SetWebhook`]: crate::payloads::SetWebhook
667 WebhookRequireHttps = "Bad Request: bad webhook: HTTPS url must be provided for webhook",
668
669 /// Occurs when bot tries to set webhook to port other than 80, 88, 443 or
670 /// 8443.
671 ///
672 /// May happen in methods:
673 /// 1. [`SetWebhook`]
674 ///
675 /// [`SetWebhook`]: crate::payloads::SetWebhook
676 BadWebhookPort = "Bad Request: bad webhook: Webhook can be set up only on ports 80, 88, 443 or 8443",
677
678 /// Occurs when bot tries to set webhook to unknown host.
679 ///
680 /// May happen in methods:
681 /// 1. [`SetWebhook`]
682 ///
683 /// [`SetWebhook`]: crate::payloads::SetWebhook
684 UnknownHost = "Bad Request: bad webhook: Failed to resolve host: Name or service not known",
685
686 /// Occurs when bot tries to set webhook to invalid URL.
687 ///
688 /// May happen in methods:
689 /// 1. [`SetWebhook`]
690 ///
691 /// [`SetWebhook`]: crate::payloads::SetWebhook
692 CantParseUrl = "Bad Request: can't parse URL",
693
694 /// Occurs when bot tries to send message with unfinished entities.
695 ///
696 /// May happen in methods:
697 /// 1. [`SendMessage`]
698 ///
699 /// [`SendMessage`]: crate::payloads::SendMessage
700 CantParseEntities(String) = "{0}" with |text: &str| {
701 if text.starts_with("Bad Request: can't parse entities") {
702 Some(text.to_owned())
703 } else {
704 None
705 }
706 },
707
708 /// Occurs when bot tries to use getUpdates while webhook is active.
709 ///
710 /// May happen in methods:
711 /// 1. [`GetUpdates`]
712 ///
713 /// [`GetUpdates`]: crate::payloads::GetUpdates
714 CantGetUpdates = "can't use getUpdates method while webhook is active",
715
716 /// Occurs when bot tries to do some in group where bot was kicked.
717 ///
718 /// May happen in methods:
719 /// 1. [`SendMessage`]
720 ///
721 /// [`SendMessage`]: crate::payloads::SendMessage
722 BotKicked = "Unauthorized: bot was kicked from a chat",
723
724 /// Occurs when bot tries to do something in a supergroup the bot was
725 /// kicked from.
726 ///
727 /// May happen in methods:
728 /// 1. [`SendMessage`]
729 ///
730 /// [`SendMessage`]: crate::payloads::SendMessage
731 BotKickedFromSupergroup = "Forbidden: bot was kicked from the supergroup chat",
732
733 /// Occurs when bot tries to do something in a channel the bot was
734 /// kicked from.
735 ///
736 /// May happen in methods:
737 /// 1. [`SendMessage`]
738 ///
739 /// [`SendMessage`]: crate::payloads::SendMessage
740 BotKickedFromChannel = "Forbidden: bot was kicked from the channel chat",
741
742 /// Occurs when bot tries to send a message to a deactivated user (i.e. a
743 /// user that was banned by telegram).
744 ///
745 /// May happen in methods:
746 /// 1. [`SendMessage`]
747 ///
748 /// [`SendMessage`]: crate::payloads::SendMessage
749 UserDeactivated = "Forbidden: user is deactivated",
750
751 /// Occurs when you tries to initiate conversation with a user.
752 ///
753 /// May happen in methods:
754 /// 1. [`SendMessage`]
755 ///
756 /// [`SendMessage`]: crate::payloads::SendMessage
757 CantInitiateConversation = "Forbidden: bot can't initiate conversation with a user",
758
759 /// Occurs when you tries to send message to bot.
760 ///
761 /// May happen in methods:
762 /// 1. [`SendMessage`]
763 ///
764 /// [`SendMessage`]: crate::payloads::SendMessage
765 CantTalkWithBots = "Unauthorized: bot can't send messages to bots",
766
767 /// Occurs when bot tries to send button with invalid http url.
768 ///
769 /// May happen in methods:
770 /// 1. [`SendMessage`]
771 ///
772 /// [`SendMessage`]: crate::payloads::SendMessage
773 WrongHttpUrl = "Bad Request: wrong HTTP URL",
774
775 /// Occurs when multiple [`GetUpdates`] calls happen at the same time.
776 ///
777 /// This can happen if
778 /// 1. You are running multiple bot instances (including on different servers/hosting platforms)
779 /// 2. You are running multiple update consumers (like `Dispatcher` or `repl`)
780 /// 3. You are calling [`GetUpdates`] yourself and the second call is done before the first one finishes
781 ///
782 /// May happen in methods:
783 /// 1. [`GetUpdates`]
784 ///
785 /// [`GetUpdates`]: crate::payloads::GetUpdates
786 TerminatedByOtherGetUpdates = "Conflict: terminated by other getUpdates request; make sure that only one bot instance \
787 is running",
788
789 /// Occurs when bot tries to get file by invalid file id.
790 ///
791 /// May happen in methods:
792 /// 1. [`GetFile`]
793 ///
794 /// [`GetFile`]: crate::payloads::GetFile
795 FileIdInvalid = "Bad Request: invalid file id",
796
797 /// Occurs when bot tries to upload a file which is larger than 50 MB using
798 /// multipart/form-data.
799 ///
800 /// May happen in methods:
801 /// 1. [`SendVideo`]
802 /// 2. [`SendDocument`]
803 ///
804 /// [`SendVideo`]: crate::payloads::SendVideo
805 /// [`SendDocument`]: crate::payloads::SendDocument
806 RequestEntityTooLarge = "Request Entity Too Large",
807
808
809 /// Error which is not known to `teloxide`.
810 ///
811 /// If you've received this error, please [open an issue] with the
812 /// description of the error.
813 ///
814 /// [open an issue]: https://github.com/teloxide/teloxide/issues/new
815 Unknown(String) = "Unknown error: {0:?}" with |text: &str| Some(text.to_owned())
816 }
817}
818
819/// This impl allows to use `?` to propagate [`DownloadError`]s in function
820/// returning [`RequestError`]s. For example:
821///
822/// ```rust
823/// # use teloxide_core::errors::{DownloadError, RequestError};
824///
825/// async fn handler() -> Result<(), RequestError> {
826/// download_file().await?; // `?` just works
827///
828/// Ok(())
829/// }
830///
831/// async fn download_file() -> Result<(), DownloadError> {
832/// /* download file here */
833/// Ok(())
834/// }
835/// ```
836impl From<DownloadError> for RequestError {
837 fn from(download_err: DownloadError) -> Self {
838 match download_err {
839 DownloadError::Network(err) => RequestError::Network(err),
840 DownloadError::Io(err) => RequestError::Io(err),
841 }
842 }
843}
844
845impl From<reqwest::Error> for DownloadError {
846 fn from(error: reqwest::Error) -> Self {
847 DownloadError::Network(Arc::new(hide_token(error)))
848 }
849}
850
851impl From<std::io::Error> for DownloadError {
852 fn from(error: std::io::Error) -> Self {
853 DownloadError::Io(Arc::new(error))
854 }
855}
856
857impl From<reqwest::Error> for RequestError {
858 fn from(error: reqwest::Error) -> Self {
859 RequestError::Network(Arc::new(hide_token(error)))
860 }
861}
862
863/// Removes the URL: credentials can appear under a custom path prefix or in a
864/// redirect URL.
865fn hide_token(error: reqwest::Error) -> reqwest::Error {
866 error.without_url()
867}
868
869#[cfg(test)]
870mod tests {
871 #[test]
872 fn custom_result() {
873 use super::ApiError;
874 use serde::Deserialize;
875
876 let cases = &[
877 ("{\"data\": \"Forbidden: bot was blocked by the user\"}", ApiError::BotBlocked),
878 ("{\"data\": \"Unauthorized\"}", ApiError::InvalidToken),
879 ("{\"data\": \"Not Found\"}", ApiError::InvalidToken),
880 (
881 "{\"data\": \"Bad Request: message is not modified: specified new message content \
882 and reply markup are exactly the same as a current content and reply markup of \
883 the message\"}",
884 ApiError::MessageNotModified,
885 ),
886 ("{\"data\": \"Bad Request: MESSAGE_ID_INVALID\"}", ApiError::MessageIdInvalid),
887 (
888 "{\"data\": \"Bad Request: message to forward not found\"}",
889 ApiError::MessageToForwardNotFound,
890 ),
891 (
892 "{\"data\": \"Bad Request: message to delete not found\"}",
893 ApiError::MessageToDeleteNotFound,
894 ),
895 (
896 "{\"data\": \"Bad Request: message to copy not found\"}",
897 ApiError::MessageToCopyNotFound,
898 ),
899 ("{\"data\": \"Bad Request: message text is empty\"}", ApiError::MessageTextIsEmpty),
900 ("{\"data\": \"Bad Request: message can't be edited\"}", ApiError::MessageCantBeEdited),
901 (
902 "{\"data\": \"Bad Request: message can't be deleted\"}",
903 ApiError::MessageCantBeDeleted,
904 ),
905 (
906 "{\"data\": \"Bad Request: message to edit not found\"}",
907 ApiError::MessageToEditNotFound,
908 ),
909 (
910 "{\"data\": \"Bad Request: there is no text in the message to edit\"}",
911 ApiError::MessageToEditHasNoText,
912 ),
913 (
914 "{\"data\": \"Bad Request: message to be replied not found\"}",
915 ApiError::MessageToReplyNotFound,
916 ),
917 (
918 "{\"data\": \"Bad Request: message identifier is not specified\"}",
919 ApiError::MessageIdentifierNotSpecified,
920 ),
921 ("{\"data\": \"Bad Request: message is too long\"}", ApiError::MessageIsTooLong),
922 ("{\"data\": \"Bad Request: MESSAGE_TOO_LONG\"}", ApiError::EditedMessageIsTooLong),
923 (
924 "{\"data\": \"Bad Request: Too much messages to send as an album\"}",
925 ApiError::TooMuchMessages,
926 ),
927 ("{\"data\": \"Bad Request: RESULTS_TOO_MUCH\"}", ApiError::TooMuchInlineQueryResults),
928 (
929 "{\"data\": \"Bad Request: poll has already been closed\"}",
930 ApiError::PollHasAlreadyClosed,
931 ),
932 (
933 "{\"data\": \"Bad Request: poll must have at least 2 option\"}",
934 ApiError::PollMustHaveMoreOptions,
935 ),
936 (
937 "{\"data\": \"Bad Request: poll can't have more than 12 options\"}",
938 ApiError::PollCantHaveMoreOptions,
939 ),
940 (
941 "{\"data\": \"Bad Request: poll options must be non-empty\"}",
942 ApiError::PollOptionsMustBeNonEmpty,
943 ),
944 (
945 "{\"data\": \"Bad Request: poll question must be non-empty\"}",
946 ApiError::PollQuestionMustBeNonEmpty,
947 ),
948 (
949 "{\"data\": \"Bad Request: poll options length must not exceed 100\"}",
950 ApiError::PollOptionsLengthTooLong,
951 ),
952 (
953 "{\"data\": \"Bad Request: poll question length must not exceed 255\"}",
954 ApiError::PollQuestionLengthTooLong,
955 ),
956 (
957 "{\"data\": \"Bad Request: message with poll to stop not found\"}",
958 ApiError::MessageWithPollNotFound,
959 ),
960 ("{\"data\": \"Bad Request: message is not a poll\"}", ApiError::MessageIsNotAPoll),
961 ("{\"data\": \"Bad Request: chat not found\"}", ApiError::ChatNotFound),
962 ("{\"data\": \"Bad Request: user not found\"}", ApiError::UserNotFound),
963 (
964 "{\"data\": \"Bad Request: chat description is not modified\"}",
965 ApiError::ChatDescriptionIsNotModified,
966 ),
967 (
968 "{\"data\": \"Bad Request: query is too old and response timeout expired or query \
969 id is invalid\"}",
970 ApiError::InvalidQueryId,
971 ),
972 ("{\"data\": \"Bad Request: BUTTON_URL_INVALID\"}", ApiError::ButtonUrlInvalid),
973 ("{\"data\": \"Bad Request: BUTTON_DATA_INVALID\"}", ApiError::ButtonDataInvalid),
974 (
975 "{\"data\": \"Bad Request: can't parse inline keyboard button: Text buttons are \
976 unallowed in the inline keyboard\"}",
977 ApiError::TextButtonsAreUnallowed,
978 ),
979 ("{\"data\": \"Bad Request: wrong file id\"}", ApiError::WrongFileId),
980 (
981 "{\"data\": \"Bad Request: wrong file identifier/HTTP URL specified\"}",
982 ApiError::WrongFileIdOrUrl,
983 ),
984 (
985 "{\"data\": \"Bad Request: failed to get HTTP URL content\"}",
986 ApiError::FailedToGetUrlContent,
987 ),
988 ("{\"data\": \"Bad Request: group is deactivated\"}", ApiError::GroupDeactivated),
989 ("{\"data\": \"Bad Request: IMAGE_PROCESS_FAILED\"}", ApiError::ImageProcessFailed),
990 (
991 "{\"data\": \"Bad Request: Photo should be uploaded as an InputFile\"}",
992 ApiError::PhotoAsInputFileRequired,
993 ),
994 ("{\"data\": \"Bad Request: STICKERSET_INVALID\"}", ApiError::InvalidStickersSet),
995 (
996 "{\"data\": \"Bad Request: sticker set name is already occupied\"}",
997 ApiError::StickerSetNameOccupied,
998 ),
999 ("{\"data\": \"Bad Request: USER_IS_BOT\"}", ApiError::StickerSetOwnerIsBot),
1000 (
1001 "{\"data\": \"Bad Request: invalid sticker set name is specified\"}",
1002 ApiError::InvalidStickerName,
1003 ),
1004 (
1005 "{\"data\": \"Bad Request: not enough rights to pin a message\"}",
1006 ApiError::NotEnoughRightsToPinMessage,
1007 ),
1008 (
1009 "{\"data\": \"Bad Request: not enough rights to manage pinned messages in the \
1010 chat\"}",
1011 ApiError::NotEnoughRightsToManagePins,
1012 ),
1013 (
1014 "{\"data\": \"Bad Request: not enough rights to change chat permissions\"}",
1015 ApiError::NotEnoughRightsToChangeChatPermissions,
1016 ),
1017 (
1018 "{\"data\": \"Bad Request: method is available only for supergroups and channel\"}",
1019 ApiError::MethodNotAvailableInPrivateChats,
1020 ),
1021 (
1022 "{\"data\": \"Bad Request: can't demote chat creator\"}",
1023 ApiError::CantDemoteChatCreator,
1024 ),
1025 ("{\"data\": \"Bad Request: can't restrict self\"}", ApiError::CantRestrictSelf),
1026 (
1027 "{\"data\": \"Bad Request: not enough rights to restrict/unrestrict chat member\"}",
1028 ApiError::NotEnoughRightsToRestrict,
1029 ),
1030 (
1031 "{\"data\": \"Bad Request: need administrator rights in the channel chat\"}",
1032 ApiError::NotEnoughRightsToPostMessages,
1033 ),
1034 ("{\"data\": \"Bad Request: PARTICIPANT_ID_INVALID\"}", ApiError::ParticipantIdInvalid),
1035 ("{\"data\": \"Bad Request: CHAT_ADMIN_REQUIRED\"}", ApiError::ChatAdminRequired),
1036 (
1037 "{\"data\": \"Bad Request: bad webhook: HTTPS url must be provided for webhook\"}",
1038 ApiError::WebhookRequireHttps,
1039 ),
1040 (
1041 "{\"data\": \"Bad Request: bad webhook: Webhook can be set up only on ports 80, \
1042 88, 443 or 8443\"}",
1043 ApiError::BadWebhookPort,
1044 ),
1045 (
1046 "{\"data\": \"Bad Request: bad webhook: Failed to resolve host: Name or service \
1047 not known\"}",
1048 ApiError::UnknownHost,
1049 ),
1050 ("{\"data\": \"Bad Request: can't parse URL\"}", ApiError::CantParseUrl),
1051 (
1052 "{\"data\": \"Bad Request: can't parse entities: SomeRandomString\"}",
1053 ApiError::CantParseEntities(
1054 "Bad Request: can't parse entities: SomeRandomString".to_owned(),
1055 ),
1056 ),
1057 (
1058 "{\"data\": \"can't use getUpdates method while webhook is active\"}",
1059 ApiError::CantGetUpdates,
1060 ),
1061 ("{\"data\": \"Unauthorized: bot was kicked from a chat\"}", ApiError::BotKicked),
1062 (
1063 "{\"data\": \"Forbidden: bot was kicked from the supergroup chat\"}",
1064 ApiError::BotKickedFromSupergroup,
1065 ),
1066 ("{\"data\": \"Forbidden: user is deactivated\"}", ApiError::UserDeactivated),
1067 (
1068 "{\"data\": \"Forbidden: bot can't initiate conversation with a user\"}",
1069 ApiError::CantInitiateConversation,
1070 ),
1071 (
1072 "{\"data\": \"Unauthorized: bot can't send messages to bots\"}",
1073 ApiError::CantTalkWithBots,
1074 ),
1075 ("{\"data\": \"Bad Request: wrong HTTP URL\"}", ApiError::WrongHttpUrl),
1076 (
1077 "{\"data\": \"Conflict: terminated by other getUpdates request; make sure that \
1078 only one bot instance is running\"}",
1079 ApiError::TerminatedByOtherGetUpdates,
1080 ),
1081 ("{\"data\": \"Bad Request: invalid file id\"}", ApiError::FileIdInvalid),
1082 ("{\"data\": \"Request Entity Too Large\"}", ApiError::RequestEntityTooLarge),
1083 ("{\"data\": \"RandomError\"}", ApiError::Unknown("RandomError".to_string())),
1084 ];
1085
1086 #[derive(Deserialize, Debug)]
1087 struct Res<T> {
1088 data: T,
1089 }
1090
1091 for (data, expected) in cases {
1092 let raw = serde_json::from_str::<Res<String>>(data).unwrap().data;
1093 let parsed = serde_json::from_str::<Res<ApiError>>(data).unwrap().data;
1094 assert_eq!(&parsed, expected);
1095
1096 let expected_error_message = match parsed {
1097 ApiError::Unknown(_) => {
1098 format!("Unknown error: \"{raw}\"")
1099 }
1100 ApiError::InvalidToken => "Invalid bot token".to_owned(),
1101 _ => raw,
1102 };
1103 assert_eq!(parsed.to_string(), expected_error_message);
1104 }
1105 }
1106}