Skip to content

Commit 0ead23a

Browse files
febus982claude
andcommitted
Add exception handling to SessionHandler.__del__
The scoped_session.remove() call could fail if the database connection is already closed during garbage collection. Wrapping in try/except with debug logging prevents errors during interpreter shutdown. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent a4e0487 commit 0ead23a

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

sqlalchemy_bind_manager/_session_handler.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
# DEALINGS IN THE SOFTWARE.
2020

2121
import asyncio
22+
import logging
2223
from contextlib import asynccontextmanager, contextmanager
2324
from typing import AsyncIterator, Iterator
2425

@@ -34,6 +35,8 @@
3435
)
3536
from sqlalchemy_bind_manager.exceptions import UnsupportedBindError
3637

38+
logger = logging.getLogger(__name__)
39+
3740

3841
class SessionHandler:
3942
scoped_session: scoped_session
@@ -45,8 +48,11 @@ def __init__(self, bind: SQLAlchemyBind):
4548
self.scoped_session = scoped_session(bind.session_class)
4649

4750
def __del__(self):
48-
if getattr(self, "scoped_session", None):
49-
self.scoped_session.remove()
51+
try:
52+
if getattr(self, "scoped_session", None):
53+
self.scoped_session.remove()
54+
except Exception:
55+
logger.debug("Failed to remove scoped session", exc_info=True)
5056

5157
@contextmanager
5258
def get_session(self, read_only: bool = False) -> Iterator[Session]:

0 commit comments

Comments
 (0)