Skip to content

Commit

Permalink
feat: ./manage.py kafka_connect exists now with CommandError in cas…
Browse files Browse the repository at this point in the history
…e of any Exception.

feat: introduce `substitute_error` decorator.

refs #34
  • Loading branch information
bodja committed Nov 6, 2024
1 parent 99cf639 commit 96d7530
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
15 changes: 15 additions & 0 deletions django_kafka/management/commands/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from collections.abc import Iterable
from functools import wraps
from typing import Callable, Type


def substitute_error(errors: Iterable[Type[Exception]], substitution: Type[Exception]) -> Callable:
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except tuple(errors) as original_error:
raise substitution from original_error
return wrapper
return decorator
2 changes: 2 additions & 0 deletions django_kafka/management/commands/kafka_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from django_kafka import kafka
from django_kafka.exceptions import DjangoKafkaError
from django_kafka.connect.connector import Connector, ConnectorStatus
from django_kafka.management.commands.errors import substitute_error
from django_kafka.utils import retry

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -61,6 +62,7 @@ def __init__(self, *args, **kwargs):
self.connectors: list[str] = []
self.has_failures = False

@substitute_error([Exception], CommandError)
def handle(self, connector, **options):
if options["list"]:
self.list_connectors()
Expand Down
21 changes: 21 additions & 0 deletions django_kafka/tests/connect/test_substitute_error.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from unittest.mock import patch, Mock

from django.core.management import CommandError
from django.test import SimpleTestCase

from django_kafka.management.commands.errors import substitute_error


class SubstituteErrorTestCase(SimpleTestCase):
def test_substitute(self):
class CustomException(Exception):
pass

errors = [ValueError, KeyError, CustomException]
decorator = substitute_error(errors, CommandError)

for error in errors:
func = Mock(side_effect=error)

with self.assertRaises(CommandError):
decorator(func)()

0 comments on commit 96d7530

Please sign in to comment.