diff --git a/CHANGES/827.bugfix b/CHANGES/827.bugfix new file mode 100644 index 00000000..f0aab059 --- /dev/null +++ b/CHANGES/827.bugfix @@ -0,0 +1 @@ +Fixed exceptions filters diff --git a/aiogram/dispatcher/filters/exception.py b/aiogram/dispatcher/filters/exception.py index f4a077f8..58f03e8c 100644 --- a/aiogram/dispatcher/filters/exception.py +++ b/aiogram/dispatcher/filters/exception.py @@ -4,6 +4,7 @@ from typing import Any, Dict, Pattern, Tuple, Type, Union, cast from pydantic import validator from aiogram.dispatcher.filters import BaseFilter +from aiogram.types import TelegramObject class ExceptionTypeFilter(BaseFilter): @@ -17,7 +18,9 @@ class ExceptionTypeFilter(BaseFilter): class Config: arbitrary_types_allowed = True - async def __call__(self, exception: Exception) -> Union[bool, Dict[str, Any]]: + async def __call__( + self, obj: TelegramObject, exception: Exception + ) -> Union[bool, Dict[str, Any]]: return isinstance(exception, self.exception) @@ -38,7 +41,9 @@ class ExceptionMessageFilter(BaseFilter): return re.compile(value) return value - async def __call__(self, exception: Exception) -> Union[bool, Dict[str, Any]]: + async def __call__( + self, obj: TelegramObject, exception: Exception + ) -> Union[bool, Dict[str, Any]]: pattern = cast(Pattern[str], self.pattern) result = pattern.match(str(exception)) if not result: diff --git a/tests/test_dispatcher/test_filters/test_exception.py b/tests/test_dispatcher/test_filters/test_exception.py index ca37b9e9..c1ffb6d8 100644 --- a/tests/test_dispatcher/test_filters/test_exception.py +++ b/tests/test_dispatcher/test_filters/test_exception.py @@ -2,7 +2,9 @@ import re import pytest +from aiogram import Dispatcher, F from aiogram.dispatcher.filters import ExceptionMessageFilter, ExceptionTypeFilter +from aiogram.types import Update pytestmark = pytest.mark.asyncio @@ -16,10 +18,10 @@ class TestExceptionMessageFilter: async def test_match(self): obj = ExceptionMessageFilter(pattern="KABOOM") - result = await obj(Exception()) + result = await obj(Update(update_id=0), exception=Exception()) assert not result - result = await obj(Exception("KABOOM")) + result = await obj(Update(update_id=0), exception=Exception("KABOOM")) assert isinstance(result, dict) assert "match_exception" in result @@ -46,6 +48,21 @@ class TestExceptionTypeFilter: async def test_check(self, exception: Exception, value: bool): obj = ExceptionTypeFilter(exception=MyException) - result = await obj(exception) + result = await obj(Update(update_id=0), exception=exception) assert result == value + + +class TestDispatchException: + async def test_handle_exception(self, bot): + dp = Dispatcher() + + @dp.update() + async def update_handler(update): + raise ValueError("KABOOM") + + @dp.errors(ExceptionMessageFilter(pattern="KABOOM")) + async def handler0(update, exception): + return "Handled" + + assert await dp.feed_update(bot, Update(update_id=0)) == "Handled"