fix: replace bare except clauses with except Exception

Bare `except:` catches BaseException including KeyboardInterrupt and
SystemExit. Replaced 29 instances with `except Exception:`.
This commit is contained in:
haosenwang1018
2026-02-25 11:49:19 +00:00
parent 1a7a8c98d9
commit adca89b973
20 changed files with 29 additions and 29 deletions

View File

@@ -509,7 +509,7 @@ class MemoryStorage:
"""Destructor to ensure connection is closed"""
try:
self.close()
except:
except Exception:
pass # Ignore errors during cleanup
# Helper methods

View File

@@ -94,7 +94,7 @@ class Ls(BaseTool):
results.append(entry + '/')
else:
results.append(entry)
except:
except Exception:
# Skip entries we can't stat
continue

View File

@@ -147,7 +147,7 @@ class SchedulerService:
return False
return now >= next_run
except:
except Exception:
return False
def _calculate_next_run(self, task: dict, from_time: datetime) -> Optional[datetime]:
@@ -195,7 +195,7 @@ class SchedulerService:
# Only return if in the future
if run_at > from_time:
return run_at
except:
except Exception:
pass
return None

View File

@@ -424,7 +424,7 @@ class SchedulerTool(BaseTool):
try:
dt = datetime.fromisoformat(run_at)
return f"一次性 ({dt.strftime('%Y-%m-%d %H:%M')})"
except:
except Exception:
return "一次性"
return "未知"
@@ -438,6 +438,6 @@ class SchedulerTool(BaseTool):
return msg.other_user_nickname or "群聊"
else:
return msg.from_user_nickname or "用户"
except:
except Exception:
pass
return "未知"

View File

@@ -72,7 +72,7 @@ class TaskStore:
with open(self.store_path, 'r') as src:
with open(backup_path, 'w') as dst:
dst.write(src.read())
except:
except Exception:
pass
# Save tasks

View File

@@ -28,7 +28,7 @@ def check_dulwich():
except ImportError:
try:
install("dulwich")
except:
except Exception:
needwait = True
try:
import dulwich

View File

@@ -323,7 +323,7 @@ def load_config():
logger.info("[INIT] override config by environ args: {}={}".format(name, value))
try:
config[name] = eval(value)
except:
except Exception:
if value == "false":
config[name] = False
elif value == "true":

View File

@@ -273,7 +273,7 @@ def get_contact(self, update=False):
'User-Agent' : config.USER_AGENT, }
try:
r = self.s.get(url, headers=headers)
except:
except Exception:
logger.info('Failed to fetch contact, that may because of the amount of your chatrooms')
for chatroom in self.get_chatrooms():
self.update_chatroom(chatroom['UserName'], detailedMember=True)

View File

@@ -21,7 +21,7 @@ async def dump_login_status(self, fileDir=None):
with open(fileDir, 'w') as f:
f.write('itchat - DELETE THIS')
os.remove(fileDir)
except:
except Exception:
raise Exception('Incorrect fileDir')
status = {
'version' : VERSION,
@@ -57,7 +57,7 @@ async def load_login_status(self, fileDir,
self.storageClass.loads(j['storage'])
try:
msgList, contactList = self.get_msg()
except:
except Exception:
msgList = contactList = None
if (msgList or contactList) is None:
self.logout()
@@ -97,6 +97,6 @@ async def load_last_login_status(session, cookiesDict):
'mm_lang': 'zh_CN',
'MM_WX_NOTIFY_STATE': '1',
'MM_WX_SOUND_STATE': '1', })
except:
except Exception:
logger.info('Load status for push login failed, we may have experienced a cookies change.')
logger.info('If you are using the newest version of itchat, you may report a bug.')

View File

@@ -330,7 +330,7 @@ async def start_receiving(self, exitCallback=None, getReceivingFnOnly=False):
retryCount = 0
except requests.exceptions.ReadTimeout:
pass
except:
except Exception:
retryCount += 1
logger.error(traceback.format_exc())
if self.receivingRetryCount < retryCount:
@@ -372,7 +372,7 @@ def sync_check(self):
# 6f:00:8a:9c:09:74:e4:d8:e0:14:bf:96:3a:56:a0:64:1b:a4:25:5d:12:f4:31:a5:30:f1:c6:48:5f:c3:75:6a:99:93
# seems like status of typing, but before I make further achievement code will remain like this
return '2'
except:
except Exception:
raise
r.raise_for_status()
regx = r'window.synccheck={retcode:"(\d+)",selector:"(\d+)"}'

View File

@@ -63,7 +63,7 @@ async def configured_reply(self, event_stream, payload, message_container):
r = await replyFn(msg)
if r is not None:
await self.send(r, msg.get('FromUserName'))
except:
except Exception:
logger.warning(traceback.format_exc())
def msg_register(self, msgType, isFriendChat=False, isGroupChat=False, isMpChat=False):

View File

@@ -287,7 +287,7 @@ def get_contact(self, update=False):
'User-Agent': config.USER_AGENT, }
try:
r = self.s.get(url, headers=headers)
except:
except Exception:
logger.info(
'Failed to fetch contact, that may because of the amount of your chatrooms')
for chatroom in self.get_chatrooms():

View File

@@ -21,7 +21,7 @@ def dump_login_status(self, fileDir=None):
with open(fileDir, 'w') as f:
f.write('itchat - DELETE THIS')
os.remove(fileDir)
except:
except Exception:
raise Exception('Incorrect fileDir')
status = {
'version' : VERSION,
@@ -57,7 +57,7 @@ def load_login_status(self, fileDir,
self.storageClass.loads(j['storage'])
try:
msgList, contactList = self.get_msg()
except:
except Exception:
msgList = contactList = None
if (msgList or contactList) is None:
self.logout()
@@ -97,6 +97,6 @@ def load_last_login_status(session, cookiesDict):
'mm_lang': 'zh_CN',
'MM_WX_NOTIFY_STATE': '1',
'MM_WX_SOUND_STATE': '1', })
except:
except Exception:
logger.info('Load status for push login failed, we may have experienced a cookies change.')
logger.info('If you are using the newest version of itchat, you may report a bug.')

View File

@@ -318,7 +318,7 @@ def start_receiving(self, exitCallback=None, getReceivingFnOnly=False):
retryCount = 0
except requests.exceptions.ReadTimeout:
pass
except:
except Exception:
retryCount += 1
logger.error(traceback.format_exc())
if self.receivingRetryCount < retryCount:
@@ -364,7 +364,7 @@ def sync_check(self):
# 6f:00:8a:9c:09:74:e4:d8:e0:14:bf:96:3a:56:a0:64:1b:a4:25:5d:12:f4:31:a5:30:f1:c6:48:5f:c3:75:6a:99:93
# seems like status of typing, but before I make further achievement code will remain like this
return '2'
except:
except Exception:
raise
r.raise_for_status()
regx = r'window.synccheck={retcode:"(\d+)",selector:"(\d+)"}'

View File

@@ -63,7 +63,7 @@ def configured_reply(self):
r = replyFn(msg)
if r is not None:
self.send(r, msg.get('FromUserName'))
except:
except Exception:
logger.warning(traceback.format_exc())
def msg_register(self, msgType, isFriendChat=False, isGroupChat=False, isMpChat=False):

View File

@@ -82,7 +82,7 @@ def check_file(fileDir):
with open(fileDir):
pass
return True
except:
except Exception:
return False
def print_qr(fileDir):
@@ -133,7 +133,7 @@ def test_connect(retryTime=5):
try:
r = requests.get(config.BASE_URL)
return True
except:
except Exception:
if i == retryTime - 1:
logger.error(traceback.format_exc())
return False

View File

@@ -208,7 +208,7 @@ class ChatGPTBot(Bot, OpenAIImage, OpenAICompatibleBot):
try:
os.remove(image_path)
logger.debug(f"[CHATGPT] Removed temp image file: {image_path}")
except:
except Exception:
pass
return Reply(ReplyType.TEXT, content)

View File

@@ -383,7 +383,7 @@ class ClaudeAPIBot(Bot, OpenAIImage):
try:
error_data = json.loads(error_text)
error_msg = error_data.get("error", {}).get("message", error_text)
except:
except Exception:
error_msg = error_text or "Unknown error"
yield {

View File

@@ -347,7 +347,7 @@ class GoogleGeminiBot(Bot):
tool_result_data = json.loads(tool_content)
else:
tool_result_data = tool_content
except:
except Exception:
tool_result_data = {"result": tool_content}
# Find the tool name from previous messages

View File

@@ -608,7 +608,7 @@ def _handle_linkai_stream_response(self, base_url, headers, body):
try:
error_data = json.loads(error_text)
error_msg = error_data.get("error", {}).get("message", error_text)
except:
except Exception:
error_msg = error_text or "Unknown error"
yield {