MTPyroger/docs/source/resources/ErrorHandling.rst

60 lines
2.0 KiB
ReStructuredText
Raw Normal View History

2018-01-06 11:18:15 +00:00
Error Handling
==============
2018-12-27 21:58:02 +00:00
Errors are inevitable when working with the API, and they must be correctly handled with ``try..except`` blocks.
2018-01-06 11:18:15 +00:00
2018-12-27 21:58:02 +00:00
There are many errors that Telegram could return, but they all fall in one of these categories
2018-01-06 11:18:15 +00:00
(which are in turn children of the :obj:`pyrogram.Error` superclass)
- :obj:`303 See Other <pyrogram.api.errors.SeeOther>`
- :obj:`400 Bad Request <pyrogram.api.errors.BadRequest>`
- :obj:`401 Unauthorized <pyrogram.api.errors.Unauthorized>`
2018-12-27 21:58:02 +00:00
- :obj:`403 Forbidden <pyrogram.api.errors.Forbidden>`
- :obj:`406 Not Acceptable <pyrogram.api.errors.NotAcceptable>`
2018-01-06 11:18:15 +00:00
- :obj:`420 Flood <pyrogram.api.errors.Flood>`
- :obj:`500 Internal Server Error <pyrogram.api.errors.InternalServerError>`
As stated above, there are really many (too many) errors, and in case Pyrogram does not know anything yet about a
specific one, it raises a special :obj:`520 Unknown Error <pyrogram.api.errors.UnknownError>` exception and logs it
in the ``unknown_errors.txt`` file. Users are invited to report these unknown errors; in later versions of Pyrogram
some kind of automatic error reporting module might be implemented.
Examples
--------
.. code-block:: python
from pyrogram.api.errors import (
BadRequest, Flood, InternalServerError,
SeeOther, Unauthorized, UnknownError
)
try:
2018-01-21 17:04:11 +00:00
...
2018-01-06 11:18:15 +00:00
except BadRequest:
pass
except Flood:
pass
except InternalServerError:
pass
except SeeOther:
pass
except Unauthorized:
pass
except UnknownError:
pass
2018-02-22 12:07:41 +00:00
Exception objects may also contain some informative values.
E.g.: :obj:`FloodWait <pyrogram.api.errors.exceptions.flood_420.FloodWait>` holds the amount of seconds you have to wait
before you can try again. The value is always stored in the ``x`` field of the returned exception object:
2018-01-06 11:18:15 +00:00
.. code-block:: python
2018-02-22 12:07:41 +00:00
import time
2018-01-06 11:18:15 +00:00
from pyrogram.api.errors import FloodWait
try:
2018-01-21 17:04:11 +00:00
...
2018-01-06 11:18:15 +00:00
except FloodWait as e:
2018-02-22 12:07:41 +00:00
time.sleep(e.x)