Add extensions for class-based error handler

This commit is contained in:
Alex Root Junior 2020-04-12 23:29:10 +03:00
parent 0fbd2819f9
commit 01c6303d67
3 changed files with 43 additions and 3 deletions

View file

@ -7,3 +7,11 @@ class ErrorHandler(BaseHandler[Exception], ABC):
""" """
Base class for errors handlers 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)

View file

@ -13,14 +13,17 @@ class MyHandler(ErrorHandler):
async def handle(self) -> Any: async def handle(self) -> Any:
log.exception( log.exception(
"Cause unexpected exception %s: %s", "Cause unexpected exception %s: %s",
self.event.__class__.__name__, self.exception_name,
self.event self.exception_message
) )
``` ```
## Extension ## 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 ## Related pages

View file

@ -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)