Add filters and class based handler for errors

This commit is contained in:
Alex Root Junior 2020-04-12 23:20:44 +03:00
parent 9e673998f0
commit 0fbd2819f9
9 changed files with 167 additions and 1 deletions

View file

@ -3,6 +3,7 @@ from typing import Dict, Tuple, Type
from .base import BaseFilter
from .command import Command, CommandObject
from .content_types import ContentTypesFilter
from .exception import ExceptionMessageFilter, ExceptionTypeFilter
from .text import Text
__all__ = (
@ -12,6 +13,8 @@ __all__ = (
"Command",
"CommandObject",
"ContentTypesFilter",
"ExceptionMessageFilter",
"ExceptionTypeFilter",
)
BUILTIN_FILTERS: Dict[str, Tuple[Type[BaseFilter], ...]] = {
@ -27,5 +30,5 @@ BUILTIN_FILTERS: Dict[str, Tuple[Type[BaseFilter], ...]] = {
"pre_checkout_query": (),
"poll": (),
"poll_answer": (),
"errors": (),
"error": (ExceptionMessageFilter, ExceptionTypeFilter),
}

View file

@ -0,0 +1,36 @@
import re
from typing import Any, Dict, Pattern, Tuple, Type, Union, cast
from pydantic import validator
from aiogram.dispatcher.filters import BaseFilter
class ExceptionTypeFilter(BaseFilter):
exception: Union[Type[Exception], Tuple[Type[Exception]]]
class Config:
arbitrary_types_allowed = True
async def __call__(self, exception: Exception) -> Union[bool, Dict[str, Any]]:
return isinstance(exception, self.exception)
class ExceptionMessageFilter(BaseFilter):
match: Union[str, Pattern[str]]
class Config:
arbitrary_types_allowed = True
@validator("match")
def _validate_match(cls, value: Union[str, Pattern[str]]) -> Union[str, Pattern[str]]:
if isinstance(value, str):
return re.compile(value)
return value
async def __call__(self, exception: Exception) -> Union[bool, Dict[str, Any]]:
pattern = cast(Pattern[str], self.match)
result = pattern.match(str(exception))
if not result:
return False
return {"match_exception": result}

View file

@ -1,6 +1,7 @@
from .base import BaseHandler, BaseHandlerMixin
from .callback_query import CallbackQueryHandler
from .chosen_inline_result import ChosenInlineResultHandler
from .error import ErrorHandler
from .inline_query import InlineQueryHandler
from .message import MessageHandler, MessageHandlerCommandMixin
from .poll import PollHandler
@ -12,6 +13,7 @@ __all__ = (
"BaseHandlerMixin",
"CallbackQueryHandler",
"ChosenInlineResultHandler",
"ErrorHandler",
"InlineQueryHandler",
"MessageHandler",
"MessageHandlerCommandMixin",

View file

@ -0,0 +1,9 @@
from abc import ABC
from aiogram.dispatcher.handler.base import BaseHandler
class ErrorHandler(BaseHandler[Exception], ABC):
"""
Base class for errors handlers
"""