Skip to content

Commit 8e14595

Browse files
authored
Added new base class for exceptions, added templates (#393)
* Added new base class for exceptions, added templates Signed-off-by: chandr-andr (Kiselev Aleksandr) <chandr@chandr.net>
1 parent 40f5579 commit 8e14595

9 files changed

+86
-15
lines changed

poetry.lock

+13-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

+1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ pytz = "*"
4747
orjson = { version = "^3", optional = true }
4848
msgpack = { version = "^1.0.7", optional = true }
4949
cbor2 = { version = "^5", optional = true }
50+
izulu = "0.5.4"
5051

5152
[tool.poetry.dev-dependencies]
5253
pytest = "^7.1.2"

taskiq/brokers/inmemory_broker.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from taskiq.abc.result_backend import AsyncResultBackend, TaskiqResult
88
from taskiq.depends.progress_tracker import TaskProgress
99
from taskiq.events import TaskiqEvents
10-
from taskiq.exceptions import TaskiqError
10+
from taskiq.exceptions import UnknownTaskError
1111
from taskiq.message import BrokerMessage
1212
from taskiq.receiver import Receiver
1313
from taskiq.utils import maybe_awaitable
@@ -156,7 +156,7 @@ async def kick(self, message: BrokerMessage) -> None:
156156
"""
157157
target_task = self.find_task(message.task_name)
158158
if target_task is None:
159-
raise TaskiqError("Unknown task.")
159+
raise UnknownTaskError(task_name=message.task_name)
160160

161161
receiver_cb = self.receiver.callback(message=message.message)
162162
if self.await_inplace:

taskiq/brokers/shared_broker.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from taskiq.abc.broker import AsyncBroker
66
from taskiq.decor import AsyncTaskiqDecoratedTask
7-
from taskiq.exceptions import TaskiqError
7+
from taskiq.exceptions import SharedBrokerListenError, SharedBrokerSendTaskError
88
from taskiq.kicker import AsyncKicker
99
from taskiq.message import BrokerMessage
1010

@@ -56,10 +56,7 @@ async def kick(self, message: BrokerMessage) -> None:
5656
:param message: message to send.
5757
:raises TaskiqError: if called.
5858
"""
59-
raise TaskiqError(
60-
"You cannot use kiq directly on shared task "
61-
"without setting the default_broker.",
62-
)
59+
raise SharedBrokerSendTaskError
6360

6461
async def listen(self) -> AsyncGenerator[bytes, None]: # type: ignore
6562
"""
@@ -69,7 +66,7 @@ async def listen(self) -> AsyncGenerator[bytes, None]: # type: ignore
6966
7067
:raises TaskiqError: if called.
7168
"""
72-
raise TaskiqError("Shared broker cannot listen")
69+
raise SharedBrokerListenError
7370

7471
def _register_task(
7572
self,

taskiq/exceptions.py

+58-1
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,103 @@
1-
class TaskiqError(Exception):
1+
from typing import Optional
2+
3+
from izulu import root
4+
5+
6+
class TaskiqError(root.Error):
27
"""Base exception for all errors."""
38

9+
__template__ = "Exception occurred"
10+
411

512
class TaskiqResultTimeoutError(TaskiqError):
613
"""Waiting for task results has timed out."""
714

15+
__template__ = "Waiting for task results has timed out, timeout={timeout}"
16+
timeout: Optional[float] = None
17+
818

919
class BrokerError(TaskiqError):
1020
"""Base class for all broker errors."""
1121

22+
__template__ = "Base exception for all broker errors"
23+
24+
25+
class ListenError(TaskiqError):
26+
"""Error if the broker is unable to listen to the queue."""
27+
28+
29+
class SharedBrokerListenError(ListenError):
30+
"""Error when someone tries to listen to the queue with shared broker."""
31+
32+
__template__ = "Shared broker cannot listen"
33+
1234

1335
class SendTaskError(BrokerError):
1436
"""Error if the broker was unable to send the task to the queue."""
1537

38+
__template__ = "Cannot send task to the queue"
39+
40+
41+
class SharedBrokerSendTaskError(SendTaskError):
42+
"""Error when someone tries to send task with shared broker."""
43+
44+
__template__ = (
45+
"You cannot use kiq directly on shared task "
46+
"without setting the default_broker."
47+
)
48+
49+
50+
class UnknownTaskError(SendTaskError):
51+
"""Error if task is unknown."""
52+
53+
__template__ = "Cannot send unknown task to the queue, task name - {task_name}"
54+
task_name: str
55+
1656

1757
class ResultBackendError(TaskiqError):
1858
"""Base class for all ResultBackend errors."""
1959

60+
__template__ = "Base exception for all result backend errors"
61+
2062

2163
class ResultGetError(ResultBackendError):
2264
"""Error if ResultBackend was unable to get result."""
2365

66+
__template__ = "Cannot get result for the task"
67+
2468

2569
class ResultSetError(ResultBackendError):
2670
"""Error if ResultBackend was unable to set result."""
2771

72+
__template__ = "Cannot set result for the task"
73+
2874

2975
class ResultIsReadyError(ResultBackendError):
3076
"""Error if ResultBackend was unable to find out if the task is ready."""
3177

78+
__template__ = "Cannot find out if the task is ready"
79+
3280

3381
class SecurityError(TaskiqError):
3482
"""Security related exception."""
3583

84+
__template__ = "Security exception occurred: {description}"
85+
description: str
86+
3687

3788
class NoResultError(TaskiqError):
3889
"""Error if user does not want to set result."""
3990

91+
__template__ = "User doesn't want to set result"
92+
4093

4194
class TaskRejectedError(TaskiqError):
4295
"""Task was rejected."""
4396

97+
__template__ = "Task was rejected"
98+
4499

45100
class ScheduledTaskCancelledError(TaskiqError):
46101
"""Scheduled task was cancelled and not sent to the queue."""
102+
103+
__template__ = "Cannot send scheduled task to the queue."

taskiq/funcs.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ async def check_task(task: AsyncTaskiqTask[Any]) -> None:
4747

4848
while task_ids:
4949
if 0 < timeout < time() - start_time:
50-
raise TaskiqResultTimeoutError("Timed out")
50+
raise TaskiqResultTimeoutError(timeout=timeout)
5151
check_tasks = []
5252
for task in tasks:
5353
check_tasks.append(loop.create_task(check_task(task)))

taskiq/receiver/receiver.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,9 @@ async def prefetcher(
353353
"""
354354
fetched_tasks: int = 0
355355
iterator = self.broker.listen()
356-
current_message: asyncio.Task[bytes | AckableMessage] = asyncio.create_task(
356+
current_message: asyncio.Task[
357+
Union[bytes, AckableMessage]
358+
] = asyncio.create_task(
357359
iterator.__anext__(), # type: ignore
358360
)
359361

taskiq/serialization.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,10 @@ def exception_to_python(
378378
if not isinstance(cls, type) or not issubclass(cls, BaseException):
379379
fake_exc_type = exc_type if exc_module is None else f"{exc_module}.{exc_type}"
380380
raise taskiq.exceptions.SecurityError(
381-
f"Expected an exception class, got {fake_exc_type} with payload {exc_msg}",
381+
description=(
382+
f"Expected an exception class, "
383+
f"got {fake_exc_type} with payload {exc_msg}"
384+
),
382385
)
383386

384387
# XXX: Without verifying `cls` is actually an exception class,

taskiq/task.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ async def wait_result(
151151
while not await self.is_ready():
152152
await asyncio.sleep(check_interval)
153153
if 0 < timeout < time() - start_time:
154-
raise TaskiqResultTimeoutError
154+
raise TaskiqResultTimeoutError(timeout=timeout)
155155
return await self.get_result(with_logs=with_logs)
156156

157157
async def get_progress(self) -> "Optional[TaskProgress[Any]]":

0 commit comments

Comments
 (0)