Skip to content
↑ ↓ move↵ openEvery page also as Markdown: add .md

Guide

Errors

Errors

Every call returns Result<_, Error>. This page is about telling a Telegram error from a network one, reading a flood wait, and retrying without sending anything twice.

Example

use std::time::Duration;
use vaegram::errors::{Error, RpcError};

let error = Error::Rpc(RpcError::new(420, "FLOOD_WAIT", Some(30)));
assert_eq!(error.flood_wait(), Some(Duration::from_secs(30)));
assert!(error.is_flood_wait());

if let Error::Rpc(rpc) = &error {
    assert_eq!((rpc.code, rpc.name.as_str(), rpc.value), (420, "FLOOD_WAIT", Some(30)));
}

let refused = Error::Rpc(RpcError::new(400, "PEER_ID_INVALID", None));
assert!(refused.is_peer_id_invalid());
assert!(!refused.is_flood_wait());

How it works

vaegram::Result<T> is std::result::Result<T, vaegram::Error>, so ? works the same everywhere.

Telegram’s errors

A request Telegram answered with an error is Error::Rpc(RpcError { code, name, value }). code works like an HTTP status (400 bad request, 401 not logged in, 420 flood limit, 500 server side), name is Telegram’s name without the trailing number, so a match checks the name and reads the number from value:

if let Error::Rpc(rpc) = error {
    match (rpc.code, rpc.name.as_str(), rpc.value) {
        (420, "FLOOD_WAIT", Some(seconds)) => println!("wait {seconds} s"),
        (400, "PEER_ID_INVALID", _) => println!("this account can't reach that chat"),
        _ => println!("{rpc}"),
    }
}

Error::is("FLOOD_WAIT") compares the name and ignores the number; Error::rpc() gives the RpcError back. There are named helpers for the errors you are likely to branch on: is_peer_id_invalid, is_message_not_modified, is_chat_admin_required, is_user_is_blocked, is_query_id_invalid, is_auth_key_unregistered, is_peer_flood and more, each documented in the API docs. is_unauthorized() covers every 401: the login is gone, or the two-step password is still needed. is_file_reference_error() covers the stale-file cases.

Network errors

The other variants mean the call didn’t get a usable answer:

  • Error::Io: a socket, DNS or file read/write failed.
  • Error::Timeout: no answer within request_timeout (30 seconds by default), so the request was abandoned.
  • Error::Disconnected: the connection closed before the answer came.
  • Error::Transport(404): the data center doesn’t know the stored login; delete the session file and start again.

A lost connection is reconnected and its waiting requests go out again without any setting. An Io, Timeout or Disconnected that reaches you was given up on, so retrying it is your decision. A Timeout doesn’t say whether Telegram ran the request: a send carries a random_id and is recognised on a retry, a call without one may run twice.

The remaining variants are local: InvalidArgument (the call can’t work as built), PeerNotFound and ChatNotJoined (the chat needs meeting or joining first), FileSize { size, limit } (too big, or empty, for this account), Unexpected (an answer vaegram can’t use), Security (a check failed, so the data was refused), MissingDependency (a handler asks for a Dep<V> nobody provided), Conversation (a conversation didn’t start or go on; the ConversationError says why), ChatMigrated { chat_id } (a group became that supergroup in Bot API mode), and Other, which carries an error of yours so a handler can return it. Error::other(e) builds one and downcast_ref::<T>() reads it back; it looks only inside Other, so match the typed variants directly.

Retrying safely

By default the client sleeps off a FLOOD_WAIT of up to 60 seconds, five times per call, and hands longer ones to you as Error::Rpc. Raise, lower or turn that off when building:

async fn client() -> Result<Client> {
    Client::builder("my_bot", 1, "api-hash")
        .flood_sleep_threshold(Duration::from_secs(120))
        .max_flood_sleeps(3)
        .start()
        .await
}

retry_policy(..) replaces both with your own RetryPolicy; NoRetries hands every failure over. When a flood wait reaches you, sleep error.flood_wait() before the same call: sending again at once draws a longer one.

Errors in handlers

A handler returns Result; with on_error registered, every Err comes there with the route, the chat, the message and the error:

use vaegram::prelude::*;

async fn setup(app: &Client) -> Result<()> {
    app.on_error(|e| async move {
        eprintln!("{:?} failed: {}", e.kind, e.error);
    });

    app.on_message(filters::text(), |msg| async move {
        match msg.answer("Hi").await {
            Ok(_) => Ok(()),
            // Waits of up to a minute were already slept off; this one is longer.
            Err(e) if e.is_flood_wait() => {
                let wait = e.flood_wait().expect("a flood wait has a duration");
                eprintln!("flood wait of {} s, sending later", wait.as_secs());
                Ok(())
            }
            Err(e) => Err(e),
        }
    });

    app.run().await
}

Without on_error, the error goes to on_event as HandlerFailed, and with neither it is printed to stderr. An error stops the later handler groups for that update.

Common mistakes

  • Matching on "FLOOD_WAIT_30": the number is in value, so the name is "FLOOD_WAIT". Use is(..) or flood_wait().
  • Treating Error::Rpc like a network error and retrying at once. A flood wait needs its sleep; a 400 won’t change.
  • Retrying a Timeout without checking what the call does: the request may have run already.
  • Catching every error in a handler and returning Ok(()). The failure disappears from on_error and from the event stream.
  • Logging error.to_string() only. error.rpc(), flood_wait() and the is_* helpers say what to do next.

See also

35 errors

FLOOD_WAIT_X420

Wait X seconds before the same request can work.

Slept off and sent again when 60 s or less, up to 5 times per call; a longer one comes back as Error::Rpc. Read the time with flood_wait().

Wait X seconds before the same request can work.

Slept off and sent again when 60 s or less, up to 5 times per call; a longer one comes back as Error::Rpc. Read the time with flood_wait().

SLOWMODE_WAIT_X420

Wait X seconds before the same request can work.

Slept off and sent again when 60 s or less, up to 5 times per call; a longer one comes back as Error::Rpc. Read the time with flood_wait().

Wait X seconds before the same request can work.

Slept off and sent again when 60 s or less, up to 5 times per call; a longer one comes back as Error::Rpc. Read the time with flood_wait().

Wait X seconds before the same request can work.

Slept off and sent again when 60 s or less, up to 5 times per call; a longer one comes back as Error::Rpc. Read the time with flood_wait().

2FA_CONFIRM_WAIT_X420

Wait X seconds before the same request can work.

Slept off and sent again when 60 s or less, up to 5 times per call; a longer one comes back as Error::Rpc. Read the time with flood_wait().

Wait one second before the same request can work.

Slept off and sent again when 60 s or less, up to 5 times per call; a longer one comes back as Error::Rpc. Read the time with flood_wait().

USER_MIGRATE_X303

The account lives on data center X.

Error::Rpc. migrate_dc() gives the data center X.

PHONE_MIGRATE_X303

The account lives on data center X.

Error::Rpc. migrate_dc() gives the data center X.

NETWORK_MIGRATE_X303

The account lives on data center X.

Error::Rpc. migrate_dc() gives the data center X.

FILE_MIGRATE_X303

This one request goes to data center X.

Error::Rpc. migrate_dc() gives the data center X.

STATS_MIGRATE_X303

This one request goes to data center X.

Error::Rpc. migrate_dc() gives the data center X.

An edit that changes nothing.

Error::Rpc. Match with e.is_message_not_modified().

MESSAGE_ID_INVALID400

The message doesn't exist, or this account can't act on it.

Error::Rpc. Match with e.is_message_id_invalid().

PEER_ID_INVALID400

The chat or user can't be used with this account.

Error::Rpc. Match with e.is_peer_id_invalid().

USER_IS_BLOCKED400

The user blocked this account, or stopped this bot.

Error::Rpc. Match with e.is_user_is_blocked().

CHAT_ADMIN_REQUIRED400

The call needs admin rights this account doesn't have.

Error::Rpc. Match with e.is_chat_admin_required().

This account can't send messages in the chat.

Error::Rpc. Match with e.is_chat_write_forbidden().

The user isn't a member of the chat.

Error::Rpc. Match with e.is_user_not_participant().

CHANNEL_PRIVATE406

The channel or supergroup can't be seen, for example after a ban.

Error::Rpc. Match with e.is_channel_private().

QUERY_ID_INVALID400

The callback or inline query was already answered or has expired.

Error::Rpc. Match with e.is_query_id_invalid().

The stored login isn't valid any more, so log in again.

Error::Rpc. Match with e.is_auth_key_unregistered() or e.is_unauthorized().

The account has two-step verification, so finish the login with its password.

Error::Rpc. Match with e.is_session_password_needed() or e.is_unauthorized().

PEER_FLOOD400

This account sent too many messages to people who don't know it, and Telegram limits it until it is lifted (check with @SpamBot).

Error::Rpc. Match with e.is_peer_flood().

AUTH_KEY_DUPLICATED406

The same login is in use from two places at once, so Telegram revoked it and this session must log in again.

Error::Rpc. Match with e.is_auth_key_duplicated().

The account is frozen, so Telegram refuses this call.

Error::Rpc. Match with e.is_frozen_method_invalid().

The user takes this only from Premium accounts.

Error::Rpc. Match with e.is_privacy_premium_required().

QUOTE_TEXT_INVALID400

The quoted text isn't in the message replied to, or doesn't fit.

Error::Rpc. Match with e.is_quote_text_invalid().

EFFECT_ID_INVALID400

The message effect doesn't exist.

Error::Rpc. Match with e.is_effect_id_invalid().

EFFECT_CHAT_INVALID400

The message effect can't be used in this chat.

Error::Rpc. Match with e.is_effect_chat_invalid().

SESSION_REVOKED401

The login is missing, revoked or deactivated; log in again.

Error::Rpc. Match with e.is_unauthorized(), which covers every 401.

USER_DEACTIVATED401

The login is missing, revoked or deactivated; log in again.

Error::Rpc. Match with e.is_unauthorized(), which covers every 401.

The file reference is stale; fetch the message or other source of the file again for a fresh one.

Error::Rpc. Match with e.is_file_reference_error(). Downloads of a known source refetch once by themselves.

The file reference is stale; fetch the message or other source of the file again for a fresh one.

Error::Rpc. Match with e.is_file_reference_error(). Downloads of a known source refetch once by themselves.

One item of an album has a stale file reference; fetch its message again for a fresh one.

Error::Rpc. Match with e.is_file_reference_error(). Downloads of a known source refetch once by themselves.

From vaegram 0.4.0-nightly.2 source (src/errors/mod.rs). Any other Telegram error is an Error::Rpc too; match it with e.is("NAME").