# 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

```rust
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`:

```rust
# use vaegram::prelude::*;
# fn f(error: &Error) {
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:

```rust,no_run
# use std::time::Duration;
# use vaegram::prelude::*;
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:

```rust,no_run
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

- [API docs](https://docs.rs/vaegram/latest/vaegram/errors/enum.Error.html) for `Error`.
- [API docs](https://docs.rs/vaegram/latest/vaegram/errors/struct.RpcError.html) for `RpcError`.
- [Telegram's error list](https://core.telegram.org/api/errors), for what an error name means.
- [Flood limits](/docs/flood-limits.md), for the per-chat limit and the waits together.