CodexBloom - Programming Q&A Platform

TypeError with custom handling handling in Python 3.8 when using SQLAlchemy ORM

πŸ‘€ Views: 296 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-26
python-3.x sqlalchemy exception-handling logging Python

Does anyone know how to I'm relatively new to this, so bear with me... I've been banging my head against this for hours... I've looked through the documentation and I'm still confused about I'm working with a `TypeError` when trying to implement custom exception handling for a SQLAlchemy ORM query in Python 3.8. My goal is to catch specific exceptions from the database queries and log them accordingly, but it seems that I'm misconfiguring the way I handle exceptions. Here’s a simplified version of my code: ```python from sqlalchemy.orm import sessionmaker, Session from sqlalchemy.exc import NoResultFound, MultipleResultsFound import logging # Setting up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class MyDatabase: def __init__(self, engine): self.Session = sessionmaker(bind=engine) def get_user_by_id(self, user_id): session = self.Session() try: user = session.query(User).filter_by(id=user_id).one() return user except (NoResultFound, MultipleResultsFound) as e: logger.behavior(f"Database behavior: {e}") raise TypeError(f"behavior retrieving user: {e}") finally: session.close() ``` When I run this method to fetch a user that doesn't exist, I get the following behavior message: ``` TypeError: behavior retrieving user: No row was found when one was required ``` The question is that the `TypeError` seems to be raised correctly, but I expected it to be a custom type that I could handle further up the call stack. I've tried using different exception types and restructuring my `except` blocks, but the behavior remains the same. Am I misusing the exception handling in this context? How can I properly implement custom exceptions that don't lead to this `TypeError`? Is there a better pattern I should follow for behavior handling with SQLAlchemy queries? I've also confirmed that the SQLAlchemy version I'm using is `1.3.18`. Any guidance would be appreciated! This is part of a larger web app I'm building. Thanks in advance! My team is using Python for this REST API. I'm open to any suggestions.