diff --git a/aiogram/dispatcher/handler/error.py b/aiogram/dispatcher/handler/error.py index dc7953bd..bc4ecdce 100644 --- a/aiogram/dispatcher/handler/error.py +++ b/aiogram/dispatcher/handler/error.py @@ -7,3 +7,11 @@ class ErrorHandler(BaseHandler[Exception], ABC): """ Base class for errors handlers """ + + @property + def exception_name(self) -> str: + return self.event.__class__.__name__ + + @property + def exception_message(self) -> str: + return str(self.event) diff --git a/docs/dispatcher/class_based_handlers/error.md b/docs/dispatcher/class_based_handlers/error.md index 94efdb93..842689a5 100644 --- a/docs/dispatcher/class_based_handlers/error.md +++ b/docs/dispatcher/class_based_handlers/error.md @@ -13,14 +13,17 @@ class MyHandler(ErrorHandler): async def handle(self) -> Any: log.exception( "Cause unexpected exception %s: %s", - self.event.__class__.__name__, - self.event + self.exception_name, + self.exception_message ) ``` ## Extension -This base handler is subclass of [BaseHandler](basics.md#basehandler) +This base handler is subclass of [BaseHandler](basics.md#basehandler) with some extensions: + +- `#!python3 self.exception_name` is alias for `#!python3 self.event.__class__.__name__` +- `#!python3 self.exception_message` is alias for `#!python3 str(self.event)` ## Related pages diff --git a/tests/test_dispatcher/test_handler/test_error.py b/tests/test_dispatcher/test_handler/test_error.py new file mode 100644 index 00000000..093d9b0a --- /dev/null +++ b/tests/test_dispatcher/test_handler/test_error.py @@ -0,0 +1,29 @@ +from typing import Any + +import pytest + +from aiogram.api.types import ( + CallbackQuery, + InlineQuery, + Poll, + PollOption, + ShippingAddress, + ShippingQuery, + User, +) +from aiogram.dispatcher.handler import ErrorHandler, PollHandler + + +class TestErrorHandler: + @pytest.mark.asyncio + async def test_extensions(self): + event = KeyError("kaboom") + + class MyHandler(ErrorHandler): + async def handle(self) -> Any: + assert self.event == event + assert self.exception_name == event.__class__.__name__ + assert self.exception_message == str(event) + return True + + assert await MyHandler(event)