Skip to content

Commit f01d9ec

Browse files
Add Exception Handling Decorator and Registry Classes
Introduce a new decorator for exception handling and a registry to manage exception handlers. The decorator allows for the registration of handlers for specific exception types, enhancing error management capabilities in the application.
1 parent 8143719 commit f01d9ec

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
2+
3+
from functools import wraps
4+
from typing import Any, Callable, Type
5+
6+
7+
from py_spring_core.exception_handler.exception_handler_registry import ExceptionHandlerRegistry
8+
9+
10+
def ExceptionHandler(exception_cls: Type[Exception]) -> Callable[[Callable[[Exception], Any]], Callable]:
11+
def decorator(func: Callable[[Exception], Any]) -> Callable:
12+
@wraps(func)
13+
def wrapper(*args, **kwargs) -> Any:
14+
return func(*args, **kwargs)
15+
ExceptionHandlerRegistry.register(exception_cls, wrapper)
16+
return wrapper
17+
18+
return decorator
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
3+
from typing import Any, Callable, Type, TypeVar
4+
5+
from loguru import logger
6+
7+
E = TypeVar('E', bound=Exception)
8+
9+
class ExceptionHandlerRegistry:
10+
_handlers: dict[str, Callable[[Any], Any]] = {}
11+
12+
@classmethod
13+
def register(cls, exception_cls: Type[E], handler: Callable[[E], Any]):
14+
key = exception_cls.__name__
15+
logger.debug(f"Registering exception handler for {key}: {handler.__name__}")
16+
if key in cls._handlers:
17+
error_message = f"Exception handler for {exception_cls} already registered"
18+
logger.error(error_message)
19+
raise RuntimeError(error_message)
20+
21+
cls._handlers[exception_cls.__name__] = handler
22+
23+
@classmethod
24+
def get_handler(cls, exception_cls: Type[E]) -> Callable[[E], Any]:
25+
return cls._handlers[exception_cls.__name__]

0 commit comments

Comments
 (0)