From 01c6303d67bd12327be1867f98ad01e17af11f16 Mon Sep 17 00:00:00 2001 From: Alex Root Junior Date: Sun, 12 Apr 2020 23:29:10 +0300 Subject: [PATCH] Add extensions for class-based error handler --- aiogram/dispatcher/handler/error.py | 8 +++++ docs/dispatcher/class_based_handlers/error.md | 9 ++++-- .../test_handler/test_error.py | 29 +++++++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 tests/test_dispatcher/test_handler/test_error.py 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)