Make exception types correspond to Python docs

This commit is contained in:
Dmitry D. Chernov 2017-12-28 09:22:28 +10:00
parent 1a746e1464
commit 6ec6967ff9
10 changed files with 29 additions and 38 deletions

View File

@ -90,7 +90,7 @@ class DocsWriter:
def end_menu(self):
"""Ends an opened menu"""
if not self.menu_began:
raise ValueError('No menu had been started in the first place.')
raise RuntimeError('No menu had been started in the first place.')
self.write('</ul>')
def write_title(self, title, level=1):

View File

@ -7,9 +7,8 @@ import re
from threading import Thread
from .common import (
ReadCancelledError, InvalidParameterError, TypeNotFoundError,
InvalidChecksumError, BrokenAuthKeyError, SecurityError,
CdnFileTamperedError
ReadCancelledError, TypeNotFoundError, InvalidChecksumError,
BrokenAuthKeyError, SecurityError, CdnFileTamperedError
)
# This imports the base errors too, as they're imported there

View File

@ -7,13 +7,6 @@ class ReadCancelledError(Exception):
super().__init__(self, 'The read operation was cancelled.')
class InvalidParameterError(Exception):
"""
Occurs when an invalid parameter is given, for example,
when either A or B are required but none is given.
"""
class TypeNotFoundError(Exception):
"""
Occurs when a type is not found, for example,

View File

@ -6,7 +6,7 @@ from datetime import datetime
from io import BufferedReader, BytesIO
from struct import unpack
from ..errors import InvalidParameterError, TypeNotFoundError
from ..errors import TypeNotFoundError
from ..tl.all_tlobjects import tlobjects
@ -22,8 +22,7 @@ class BinaryReader:
elif stream:
self.stream = stream
else:
raise InvalidParameterError(
'Either bytes or a stream must be provided')
raise ValueError('Either bytes or a stream must be provided')
self.reader = BufferedReader(self.stream)
self._last = None # Should come in handy to spot -404 errors
@ -110,7 +109,7 @@ class BinaryReader:
elif value == 0xbc799737: # boolFalse
return False
else:
raise ValueError('Invalid boolean code {}'.format(hex(value)))
raise RuntimeError('Invalid boolean code {}'.format(hex(value)))
def tgread_date(self):
"""Reads and converts Unix time (used by Telegram)
@ -141,7 +140,7 @@ class BinaryReader:
def tgread_vector(self):
"""Reads a vector (a list) of Telegram objects."""
if 0x1cb5c415 != self.read_int(signed=False):
raise ValueError('Invalid constructor code, vector was expected')
raise RuntimeError('Invalid constructor code, vector was expected')
count = self.read_int()
return [self.tgread_object() for _ in range(count)]

View File

@ -26,7 +26,7 @@ class TcpClient:
elif isinstance(timeout, (int, float)):
self.timeout = float(timeout)
else:
raise ValueError('Invalid timeout type', type(timeout))
raise TypeError('Invalid timeout type: {}'.format(type(timeout)))
def _recreate_socket(self, mode):
if self.proxy is None:

View File

@ -84,7 +84,7 @@ class TelegramBareClient:
**kwargs):
"""Refer to TelegramClient.__init__ for docs on this method"""
if not api_id or not api_hash:
raise PermissionError(
raise ValueError(
"Your API ID or Hash cannot be empty or None. "
"Refer to Telethon's wiki for more information.")
@ -94,7 +94,7 @@ class TelegramBareClient:
if isinstance(session, str) or session is None:
session = Session.try_load_or_create_new(session)
elif not isinstance(session, Session):
raise ValueError(
raise TypeError(
'The given session must be a str or a Session instance.'
)
@ -421,11 +421,11 @@ class TelegramBareClient:
"""Invokes (sends) a MTProtoRequest and returns (receives) its result.
The invoke will be retried up to 'retries' times before raising
ValueError().
RuntimeError().
"""
if not all(isinstance(x, TLObject) and
x.content_related for x in requests):
raise ValueError('You can only invoke requests, not types!')
raise TypeError('You can only invoke requests, not types!')
# For logging purposes
if len(requests) == 1:
@ -486,7 +486,7 @@ class TelegramBareClient:
else:
sender.connect()
raise ValueError('Number of retries reached 0.')
raise RuntimeError('Number of retries reached 0.')
finally:
if sender != self._sender:
sender.disconnect() # Close temporary connections
@ -682,8 +682,8 @@ class TelegramBareClient:
if progress_callback:
progress_callback(stream.tell(), file_size)
else:
raise ValueError('Failed to upload file part {}.'
.format(part_index))
raise RuntimeError(
'Failed to upload file part {}.'.format(part_index))
finally:
stream.close()
@ -853,7 +853,7 @@ class TelegramBareClient:
:return:
"""
if self._spawn_read_thread and not self._on_read_thread():
raise ValueError('Can only idle if spawn_read_thread=False')
raise RuntimeError('Can only idle if spawn_read_thread=False')
for sig in stop_signals:
signal(sig, self._signal_handler)

View File

@ -13,9 +13,8 @@ except ImportError:
from . import TelegramBareClient
from . import helpers, utils
from .errors import (
RPCError, UnauthorizedError, InvalidParameterError, PhoneCodeEmptyError,
PhoneCodeExpiredError, PhoneCodeHashEmptyError, PhoneCodeInvalidError,
LocationInvalidError
RPCError, UnauthorizedError, PhoneCodeEmptyError, PhoneCodeExpiredError,
PhoneCodeHashEmptyError, PhoneCodeInvalidError, LocationInvalidError
)
from .network import ConnectionMode
from .tl import TLObject
@ -381,7 +380,7 @@ class TelegramClient(TelegramBareClient):
if parse_mode in {'md', 'markdown'}:
message, msg_entities = markdown.parse(message)
else:
raise ValueError('Unknown parsing mode', parse_mode)
raise ValueError('Unknown parsing mode: {}'.format(parse_mode))
else:
msg_entities = []
@ -572,7 +571,7 @@ class TelegramClient(TelegramBareClient):
"""
if max_id is None:
if not messages:
raise InvalidParameterError(
raise ValueError(
'Either a message list or a max_id must be provided.')
if hasattr(message, '__iter__'):
@ -600,7 +599,7 @@ class TelegramClient(TelegramBareClient):
# hex(crc32(b'Message')) = 0x790009e3
return reply_to.id
raise ValueError('Invalid reply_to type: ', type(reply_to))
raise TypeError('Invalid reply_to type: {}'.format(type(reply_to)))
# endregion
@ -1053,7 +1052,7 @@ class TelegramClient(TelegramBareClient):
if isinstance(entity, str):
return self._get_entity_from_string(entity)
raise ValueError(
raise TypeError(
'Cannot turn "{}" into any entity (user or chat)'.format(entity)
)
@ -1128,7 +1127,7 @@ class TelegramClient(TelegramBareClient):
pass
if not is_peer:
raise ValueError(
raise TypeError(
'Cannot turn "{}" into an input entity.'.format(peer)
)

View File

@ -21,7 +21,7 @@ class Draft:
@classmethod
def _from_update(cls, client, update):
if not isinstance(update, UpdateDraftMessage):
raise ValueError(
raise TypeError(
'You can only create a new `Draft` from a corresponding '
'`UpdateDraftMessage` object.'
)

View File

@ -97,7 +97,8 @@ class TLObject:
if isinstance(data, str):
data = data.encode('utf-8')
else:
raise ValueError('bytes or str expected, not', type(data))
raise TypeError(
'bytes or str expected, not {}'.format(type(data)))
r = []
if len(data) < 254:

View File

@ -67,13 +67,13 @@ def get_extension(media):
def _raise_cast_fail(entity, target):
raise ValueError('Cannot cast {} to any kind of {}.'
.format(type(entity).__name__, target))
raise TypeError('Cannot cast {} to any kind of {}.'.format(
type(entity).__name__, target))
def get_input_peer(entity, allow_self=True):
"""Gets the input peer for the given "entity" (user, chat or channel).
A ValueError is raised if the given entity isn't a supported type."""
A TypeError is raised if the given entity isn't a supported type."""
if not isinstance(entity, TLObject):
_raise_cast_fail(entity, 'InputPeer')