🎨 优化异常处理

This commit is contained in:
洛水居室 2022-10-21 15:06:24 +08:00
parent 57f0029a42
commit e6c25aaa98
No known key found for this signature in database
GPG Key ID: C9DE87DA724B88FC
5 changed files with 29 additions and 12 deletions

View File

@ -17,7 +17,7 @@ class NetworkException(APIHelperException):
pass
class TimedOut(APIHelperException):
class APIHelperTimedOut(APIHelperException):
pass

View File

@ -2,7 +2,7 @@ from typing import Union
import httpx
from modules.apihelper.error import NetworkException, ResponseException, TimedOut
from modules.apihelper.error import NetworkException, ResponseException, APIHelperTimedOut
from modules.apihelper.request.httpxrequest import HTTPXRequest
from modules.apihelper.typedefs import POST_DATA, JSON_DATA
@ -14,7 +14,7 @@ class HOYORequest(HTTPXRequest):
try:
response = await self._client.get(url=url, *args, **kwargs)
except httpx.TimeoutException as err:
raise TimedOut from err
raise APIHelperTimedOut from err
except httpx.HTTPError as exc:
raise NetworkException(f"Unknown error in HTTP implementation: {repr(exc)}") from exc
if response.is_error:

View File

@ -13,6 +13,7 @@ from core.base.mtproto import MTProto
from core.bot import bot
from core.plugin import Plugin, handler
from core.quiz import QuizService
from utils.decorators.error import error_callable
from utils.decorators.restricts import restricts
from utils.log import logger
from utils.random import MT19937Random
@ -104,6 +105,7 @@ class GroupJoiningVerification(Plugin):
logger.exception(exc)
@handler(CallbackQueryHandler, pattern=r"^auth_admin\|", block=False)
@error_callable
@restricts(without_overlapping=True)
async def admin(self, update: Update, context: CallbackContext) -> None:
async def admin_callback(callback_query_data: str) -> Tuple[str, int]:
@ -160,6 +162,7 @@ class GroupJoiningVerification(Plugin):
schedule.remove()
@handler(CallbackQueryHandler, pattern=r"^auth_challenge\|", block=False)
@error_callable
@restricts(without_overlapping=True)
async def query(self, update: Update, context: CallbackContext) -> None:
async def query_callback(callback_query_data: str) -> Tuple[int, bool, str, str]:
@ -229,6 +232,7 @@ class GroupJoiningVerification(Plugin):
schedule.remove()
@handler.message.new_chat_members(priority=2)
@error_callable
async def new_mem(self, update: Update, context: CallbackContext) -> None:
message = update.effective_message
chat = message.chat

View File

@ -64,9 +64,6 @@ class ErrorHandler(Plugin):
if "make sure that only one bot instance is running" in tb_string:
logger.error("其他机器人在运行,请停止!")
return
if "Message is not modified" in tb_string:
logger.error("消息未修改")
return
await context.bot.send_document(
chat_id=notice_chat_id,
document=open(log_file, "rb"),

View File

@ -9,7 +9,7 @@ from telegram import Update, ReplyKeyboardRemove
from telegram.error import BadRequest, TimedOut, Forbidden
from telegram.ext import CallbackContext, ConversationHandler
from modules.apihelper.error import APIHelperException, ReturnCodeError
from modules.apihelper.error import APIHelperException, ReturnCodeError, APIHelperTimedOut
from utils.error import UrlResourcesNotFoundError
from utils.log import logger
@ -17,16 +17,14 @@ from utils.log import logger
async def send_user_notification(update: Update, _: CallbackContext, text: str):
if update.inline_query is not None: # 忽略 inline_query
return
effective_user = update.effective_user
user = update.effective_user
message = update.effective_message
chat = update.effective_chat
if message is None:
update_str = update.to_dict() if isinstance(update, Update) else str(update)
logger.warning("错误的消息类型\n" + json.dumps(update_str, indent=2, ensure_ascii=False))
return
chat = message.chat
logger.info(
f"尝试通知用户 {effective_user.full_name}[{effective_user.id}] " f"{chat.full_name}[{chat.id}]" f"的 错误信息[{text}]"
)
logger.info(f"尝试通知用户 {user.full_name}[{user.id}] " f"{chat.full_name}[{chat.id}]" f"的 错误信息[{text}]")
try:
await message.reply_text(text, reply_markup=ReplyKeyboardRemove(), allow_sending_without_reply=True)
except BadRequest as exc:
@ -42,6 +40,14 @@ async def send_user_notification(update: Update, _: CallbackContext, text: str):
pass
def telegram_warning(update: Update, text: str):
user = update.effective_user
message = update.effective_message
chat = update.effective_chat
msg = f"{text}\n" f"user_id[{user.id}] chat_id[{chat.id}] message_id[{message.id}] "
logger.warning(msg)
def error_callable(func: Callable) -> Callable:
"""Plugins 错误处理修饰器
@ -107,12 +113,22 @@ def error_callable(func: Callable) -> Callable:
except ReturnCodeError as exc:
await send_user_notification(update, context, f"出错了呜呜呜 ~ API请求错误 错误信息为 {exc.message}")
return ConversationHandler.END
except APIHelperTimedOut:
logger.warning("APIHelperException")
await send_user_notification(update, context, "出错了呜呜呜 ~ API请求超时")
except APIHelperException as exc:
logger.error("APIHelperException")
logger.exception(exc)
await send_user_notification(update, context, "出错了呜呜呜 ~ API请求错误")
return ConversationHandler.END
except BadRequest as exc:
if "Replied message not found" in exc.message:
telegram_warning(update, exc.message)
await send_user_notification(update, context, "气死我了!怎么有人喜欢发一个命令就秒删了!")
return ConversationHandler.END
if "Message is not modified" in exc.message:
telegram_warning(update, exc.message)
return ConversationHandler.END
logger.error("python-telegram-bot 请求错误")
logger.exception(exc)
await send_user_notification(update, context, "出错了呜呜呜 ~ telegram-bot-api请求错误")