refactor: replace try-except blocks with contextlib.suppress for cleaner error handling across multiple files

This commit is contained in:
Jack Lu
2026-05-01 19:30:11 +08:00
committed by Xubin Ren
parent 1c24f10236
commit d9800ecdd2
27 changed files with 98 additions and 195 deletions
+5 -9
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import os
import sys
from contextlib import suppress
from nanobot import __version__
from nanobot.bus.events import OutboundMessage
@@ -50,16 +51,15 @@ async def cmd_status(ctx: CommandContext) -> OutboundMessage:
loop = ctx.loop
session = ctx.session or loop.sessions.get_or_create(ctx.key)
ctx_est = 0
try:
with suppress(Exception):
ctx_est, _ = loop.consolidator.estimate_session_prompt_tokens(session)
except Exception:
pass
if ctx_est <= 0:
ctx_est = loop._last_usage.get("prompt_tokens", 0)
# Fetch web search provider usage (best-effort, never blocks the response)
search_usage_text: str | None = None
try:
# Never let usage fetch break /status
with suppress(Exception):
from nanobot.utils.searchusage import fetch_search_usage
web_cfg = getattr(loop, "web_config", None)
search_cfg = getattr(web_cfg, "search", None) if web_cfg else None
@@ -68,14 +68,10 @@ async def cmd_status(ctx: CommandContext) -> OutboundMessage:
api_key = getattr(search_cfg, "api_key", "") or None
usage = await fetch_search_usage(provider=provider, api_key=api_key)
search_usage_text = usage.format()
except Exception:
pass # Never let usage fetch break /status
active_tasks = loop._active_tasks.get(ctx.key, [])
task_count = sum(1 for t in active_tasks if not t.done())
try:
with suppress(Exception):
task_count += loop.subagents.get_running_count_by_session(ctx.key)
except Exception:
pass
return OutboundMessage(
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,