♻️ 重写 Aiohttp 超时抛出异常

Co-authored-by: Karako <karakohear@gmail.com>
This commit is contained in:
omg-xtao 2022-09-27 23:52:32 +08:00 committed by 洛水居室
parent 2534f81d3f
commit ec71907701
No known key found for this signature in database
GPG Key ID: C9DE87DA724B88FC
5 changed files with 41 additions and 0 deletions

View File

@ -35,6 +35,7 @@ from utils.decorators.restricts import restricts
from utils.helpers import url_to_file
from utils.log import logger
from utils.models.base import RegionEnum
from utils.patch.aiohttp import AioHttpTimeoutException
assets = Assets(lang="chs")
@ -53,6 +54,8 @@ class PlayerCards(Plugin, BasePlugin):
return "Enka.Network 服务请求错误,请稍后重试"
except Forbidden:
return "Enka.Network 服务请求被拒绝,请稍后重试"
except AioHttpTimeoutException:
return "Enka.Network 服务请求超时,请稍后重试"
except HTTPException:
return "Enka.Network HTTP 服务请求错误,请稍后重试"
except UIDNotFounded:

1
utils/__init__.py Normal file
View File

@ -0,0 +1 @@
from utils.patch import *

1
utils/patch/__init__.py Normal file
View File

@ -0,0 +1 @@
from utils.patch import aiohttp

19
utils/patch/aiohttp.py Normal file
View File

@ -0,0 +1,19 @@
import asyncio
import aiohttp
from utils.patch.methods import patch, patchable
from typing import Optional
class AioHttpTimeoutException(asyncio.TimeoutError):
pass
@patch(aiohttp.helpers.TimerContext)
class TimerContext:
@patchable
def __exit__(self, *args, **kwargs) -> Optional[bool]:
try:
return self.old___exit__(*args, **kwargs)
except asyncio.TimeoutError:
raise AioHttpTimeoutException from None

17
utils/patch/methods.py Normal file
View File

@ -0,0 +1,17 @@
def patch(obj):
def is_patchable(item):
return getattr(item[1], 'patchable', False)
def wrapper(container):
for name, func in filter(is_patchable, container.__dict__.items()):
old = getattr(obj, name, None)
setattr(obj, f'old_{name}', old)
setattr(obj, name, func)
return container
return wrapper
def patchable(func):
func.patchable = True
return func