全局异常捕获,特别是IOClosed错误,避免服务器崩溃

This commit is contained in:
CakeCN
2026-01-07 01:06:13 +08:00
parent a3b3018de7
commit 8aa567cdf2
2 changed files with 47 additions and 8 deletions

View File

@@ -1,5 +1,32 @@
import eventlet
eventlet.monkey_patch() # 进行猴子补丁操作
import logging
# 配置 eventlet 日志,抑制 IOClosed 等错误日志
logging.getLogger('eventlet.hubs').setLevel(logging.CRITICAL)
logging.getLogger('eventlet.greenio').setLevel(logging.CRITICAL)
# 进行猴子补丁操作
eventlet.monkey_patch()
# 配置 eventlet hub 以更优雅地处理 IOClosed 错误
try:
from eventlet.hubs import hub
# 保存原始的 handle_error 方法
original_handle_error = hub.Hub.handle_error
def custom_handle_error(self, context, type, value, tb):
# 忽略 IOClosed 错误
if type.__name__ == 'IOClosed' and 'Operation on closed file' in str(value):
return
# 其他错误调用原始方法
original_handle_error(self, context, type, value, tb)
# 替换原始方法
hub.Hub.handle_error = custom_handle_error
except Exception as e:
# 如果修改失败,忽略错误
pass
from flask import Flask
from .views.routes import main_bp
from .views.file import file_bp