How to catch exceptions caused by the SQLAlchemy component?


Hi there,

I am playing around with APIStar and I really like it. Currently, I am prototyping a microservice. Persistence is handled by the SQLAlchemy component.

I created a model with some columns. One column has a UNIQUE constraint defined (using the unique=True argument).

To glue things together, I added an API endpoint with a corresponding handler function, e.g.:

def create_item(item: Item, session: Session):
    # ....
    # ...

When I ingest data that violate the uniqueness-constraint, SQLAlchemy (rightly) raises an Exception, causing the component to rollback. However, I want to catch the Exception raised by the Component (e.g. this one) and act on it (e.g. returning a custom error message).

Wrapping my handler function in a try/except block does not work. How should / can this be done?

If this is a bug, I am more than happy to file it on Github and try to put out a PR for it.


Are you catching the right things?

except (exc.IntegrityError,  exc.InvalidRequestError) as error:
    data = {'foo': 1}
    return Response(data, status=400)