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): def end_menu(self):
"""Ends an opened menu""" """Ends an opened menu"""
if not self.menu_began: 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>') self.write('</ul>')
def write_title(self, title, level=1): def write_title(self, title, level=1):

View File

@ -7,9 +7,8 @@ import re
from threading import Thread from threading import Thread
from .common import ( from .common import (
ReadCancelledError, InvalidParameterError, TypeNotFoundError, ReadCancelledError, TypeNotFoundError, InvalidChecksumError,
InvalidChecksumError, BrokenAuthKeyError, SecurityError, BrokenAuthKeyError, SecurityError, CdnFileTamperedError
CdnFileTamperedError
) )
# This imports the base errors too, as they're imported there # 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.') 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): class TypeNotFoundError(Exception):
""" """
Occurs when a type is not found, for example, 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 io import BufferedReader, BytesIO
from struct import unpack from struct import unpack
from ..errors import InvalidParameterError, TypeNotFoundError from ..errors import TypeNotFoundError
from ..tl.all_tlobjects import tlobjects from ..tl.all_tlobjects import tlobjects
@ -22,8 +22,7 @@ class BinaryReader:
elif stream: elif stream:
self.stream = stream self.stream = stream
else: else:
raise InvalidParameterError( raise ValueError('Either bytes or a stream must be provided')
'Either bytes or a stream must be provided')
self.reader = BufferedReader(self.stream) self.reader = BufferedReader(self.stream)
self._last = None # Should come in handy to spot -404 errors self._last = None # Should come in handy to spot -404 errors
@ -110,7 +109,7 @@ class BinaryReader:
elif value == 0xbc799737: # boolFalse elif value == 0xbc799737: # boolFalse
return False return False
else: else:
raise ValueError('Invalid boolean code {}'.format(hex(value))) raise RuntimeError('Invalid boolean code {}'.format(hex(value)))
def tgread_date(self): def tgread_date(self):
"""Reads and converts Unix time (used by Telegram) """Reads and converts Unix time (used by Telegram)
@ -141,7 +140,7 @@ class BinaryReader:
def tgread_vector(self): def tgread_vector(self):
"""Reads a vector (a list) of Telegram objects.""" """Reads a vector (a list) of Telegram objects."""
if 0x1cb5c415 != self.read_int(signed=False): 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() count = self.read_int()
return [self.tgread_object() for _ in range(count)] return [self.tgread_object() for _ in range(count)]

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -67,13 +67,13 @@ def get_extension(media):
def _raise_cast_fail(entity, target): def _raise_cast_fail(entity, target):
raise ValueError('Cannot cast {} to any kind of {}.' raise TypeError('Cannot cast {} to any kind of {}.'.format(
.format(type(entity).__name__, target)) type(entity).__name__, target))
def get_input_peer(entity, allow_self=True): def get_input_peer(entity, allow_self=True):
"""Gets the input peer for the given "entity" (user, chat or channel). """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): if not isinstance(entity, TLObject):
_raise_cast_fail(entity, 'InputPeer') _raise_cast_fail(entity, 'InputPeer')