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

This commit is contained in:
Jack Lu authored and Xubin Ren committed 2026-05-01 19:30:11 +08:00
1 parent 1c24f10236
commit d9800ecdd2
27 files changed
+98 -195

No files matched your search

+6 -12
View File
@@ -7,6 +7,7 @@ import json
import os
import re
import weakref
from contextlib import suppress
import tiktoken
from datetime import datetime
from pathlib import Path
@@ -296,10 +297,8 @@ class MemoryStore:
def _next_cursor(self) -> int:
"""Read the current cursor counter and return the next value."""
if self._cursor_file.exists():
try:
with suppress(ValueError, OSError):
return int(self._cursor_file.read_text(encoding="utf-8").strip()) + 1
except (ValueError, OSError):
pass
# Fast path: trust the tail when intact. Otherwise scan the whole
# file and take ``max`` — that stays correct even if the monotonic
# invariant was broken by external writes.
@@ -328,7 +327,7 @@ class MemoryStore:
def _read_entries(self) -> list[dict[str, Any]]:
"""Read all entries from history.jsonl."""
entries: list[dict[str, Any]] = []
try:
with suppress(FileNotFoundError):
with open(self.history_file, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
@@ -337,8 +336,7 @@ class MemoryStore:
entries.append(json.loads(line))
except json.JSONDecodeError:
continue
except FileNotFoundError:
pass
return entries
def _read_last_entry(self) -> dict[str, Any] | None:
@@ -374,14 +372,12 @@ class MemoryStore:
# On Windows, opening a directory with O_RDONLY raises
# PermissionError — skip the dir sync there (NTFS
# journals metadata synchronously).
try:
with suppress(PermissionError):
fd = os.open(str(self.history_file.parent), os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
except PermissionError:
pass # Windows — directory fsync not supported
except BaseException:
tmp_path.unlink(missing_ok=True)
raise
@@ -390,10 +386,8 @@ class MemoryStore:
def get_last_dream_cursor(self) -> int:
if self._dream_cursor_file.exists():
try:
with suppress(ValueError, OSError):
return int(self._dream_cursor_file.read_text(encoding="utf-8").strip())
except (ValueError, OSError):
pass
return 0
def set_last_dream_cursor(self, cursor: int) -> None: