Skip to content

Commit

Permalink
utils: added decorator to simplify common error handling
Browse files Browse the repository at this point in the history
- we add a simple decorator which allows arguments for the exceptions to catch and also
for the exception to later reraise from the caught exception
- this simplifies the code within the version manager when we deal with versions that could be integer strings
  • Loading branch information
nosahama committed May 29, 2024
1 parent d0ce5b9 commit 3cba05d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
18 changes: 18 additions & 0 deletions karapace/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from types import MappingProxyType
from typing import AnyStr, cast, IO, Literal, NoReturn, overload, TypeVar

import functools
import importlib
import kafka.client_async
import logging
Expand Down Expand Up @@ -214,6 +215,23 @@ def convert_to_int(object_: dict, key: str, content_type: str) -> None:
)


def catch_and_raise_error(to_catch: tuple[Exception], to_raise: Exception):
def wrapper(f):
@functools.wraps(f)
def catcher(*args, **kwargs):
try:
value = f(*args, **kwargs)
if not value:
raise to_raise
return value
except to_catch as exc:
raise to_raise from exc

return catcher

return wrapper


class KarapaceKafkaClient(KafkaClient):
def __init__(self, **configs):
kafka.client_async.BrokerConnection = KarapaceBrokerConnection
Expand Down
29 changes: 29 additions & 0 deletions tests/unit/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
karapace - Test utils
Copyright (c) 2024 Aiven Ltd
See LICENSE for details
"""

from karapace.utils import catch_and_raise_error

import pytest


def test_catch_and_raise_error():
class RaiseMe(Exception):
pass

@catch_and_raise_error(to_catch=(ValueError,), to_raise=RaiseMe)
def v():
int("not a number")

with pytest.raises(RaiseMe):
v()

@catch_and_raise_error(to_catch=(ZeroDivisionError,), to_raise=RaiseMe)
def z():
_ = 100 / 0

with pytest.raises(RaiseMe):
z()

0 comments on commit 3cba05d

Please sign in to comment.